• Advertisement
Sign in to follow this  

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 this post


Link to post
Share on other sites
Advertisement

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);
})();

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Advertisement