• 10
• 12
• 12
• 14
• 15

# setInterval

## Recommended Posts

I'm just wondering if anyone knows off the top of their head the answer to the following.

When I use setInterval( function(){ // do something // } , 150 ).  is the function executed once every 150 milliseconds like clock work, or is the function executed 150 milliseconds after the function is finished doing its work??  let's say the work in question take 300 milliseconds.  Does it go like:

1.  150 milli >> execute function

2.  +300 milli >> function finishes

3.  +0 milli >> execute function ( because 300 is greater than 150 ) OR

3.  + 150 milli >> execute function

##### Share on other sites

The truth is somewhere inbetween the two. :) setInterval afaik doesn't care about how long the passed callback runs, and it won't fire exactly on given delays either. With the given example, the browser will queue up the passed callback for execution every 150ms, but it will only execute when the execution "thread" doesn't have anything else important to run. (This is why the age old setTimeout with zero delay hack works, a 0 as a delay in this case doesn't mean it will execute immediately, it just means that it will run as soon as possible when nothing else is running.)

Sidenote: it is perfectly possible to do the second option you described with recursive setTimeouts, e.g:

(function func(){
setTimeout(function(){
//code
func();
}, delay);
})();