Asked 7 years ago
18 Jan 2017
Views 2197
web-api

web-api posted

setInterval vs setTimeout

difference between setInterval and setTimeout in JavaScript ?
pros and cons of setInterval and setTimeout over each other ?
which one is best to use or more useful in between setInterval and setTimeout ?
Rasi

Rasi
answered Nov 30 '-1 00:00

setInterval is function in JavaScript which call per interval .
syntax ::
setInterval (function(){},intervalTimeInMiliSecond)
setInterval have two argument , first is function to call per interval and second argument is time interval which in millisecond.


setTimeout is function in JavaScript which call once after given time .
syntax ::
setTimeout (function(){},timeoutMiliSecond)
setTimeout have two argument . first is function to call after timeout . second argument is time in millisecond which is time need to pass before call first argument function.

big difference between is one run per interval . it will remain on until we make clearInterval , and setTimeout is run once when given time passed
setInterval for repeat action for given interval and setTimeout is one time action after given time

setTimeout mostly used to execute function after some delay. it used to buffer delay before run function.

setInterval is means n time of running setTimeout for given time passed.
so we can say this

var sEtInterval=function(func,interval){
setTimeout(func,interval);
sEtInterval(func,interval);
}

setInterval is like recursion of setTimeout for n time until it interrupted
in above sEtInterval(alert('me'),1200)=setInterval(alert('me'),1200)
noob

noob
answered Nov 30 '-1 00:00

avoid to use setInterval , in some cases people forget to make exit code for setInterval and make interval run for infinite and result is page crash. use clearInterval with setInterval to avoid that type of issue .

i like personally setTimeout . its run once when time elapsed and cause no harm for file .
Post Answer