Problems with Looping through window.setInterval

Look at this code. What do you expect to be the outcome?

var d = new Date();
var r = [];
for(var j=0,k=2;j<k ;j++) {
    window.setInterval(function()
    {
        var next = new Date();
        r.push(next.getTime() - d.getTime());
    },1000);
}

Every 1000 milliseconds (1 second), the r array should have three delta timestamps added into it (one for each interval set in the for loop). In FireFox, however, there are exactly nine delta timestamps added per second. If you set k=10, the result is one hundred delta timestamps per second. If anyone has the answer, I am curious, even if the result is that I'm an idiot. It seems to work correctly in Internet Explorer 7. Thanks for your help, internet.

VN:F [1.9.3_1094]
Rating: 3.3/5 (3 votes cast)
Problems with Looping through window.setInterval, 3.3 out of 5 based on 3 ratings
This entry was posted in JavaScript, Web Browsers and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted January 15, 2008 at 6:49 pm | Permalink

    Um… do you mean to be using window.setTimeout rather than window.setInterval? Using setInterval will cause your internal function to execute once every 100 milliseconds. And will add lots of time stamps to the array.

  2. Zach Leatherman
    Posted January 16, 2008 at 8:08 pm | Permalink

    I meant to use setInterval. Using the for loop above, I should have my internal payload function execute in 3 separate 1 second interval timers. So every second, I should get 3 entries added into the r array. But, I’m getting 9 entries added every second, which is confusing to me. There should be only 3 timers, not 9.

One Trackback

  1. [...] 12.23 Problems with Looping through window.setInterval [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Additional comments powered by BackType