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)…


This content originally appeared on Zach Leatherman and was authored by Zach Leatherman

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.


This content originally appeared on Zach Leatherman and was authored by Zach Leatherman


Print Share Comment Cite Upload Translate Updates
APA

Zach Leatherman | Sciencx (2007-12-23T06:00:00+00:00) Problems with Looping through window.setInterval. Retrieved from https://www.scien.cx/2007/12/23/problems-with-looping-through-window-setinterval/

MLA
" » Problems with Looping through window.setInterval." Zach Leatherman | Sciencx - Sunday December 23, 2007, https://www.scien.cx/2007/12/23/problems-with-looping-through-window-setinterval/
HARVARD
Zach Leatherman | Sciencx Sunday December 23, 2007 » Problems with Looping through window.setInterval., viewed ,<https://www.scien.cx/2007/12/23/problems-with-looping-through-window-setinterval/>
VANCOUVER
Zach Leatherman | Sciencx - » Problems with Looping through window.setInterval. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2007/12/23/problems-with-looping-through-window-setinterval/
CHICAGO
" » Problems with Looping through window.setInterval." Zach Leatherman | Sciencx - Accessed . https://www.scien.cx/2007/12/23/problems-with-looping-through-window-setinterval/
IEEE
" » Problems with Looping through window.setInterval." Zach Leatherman | Sciencx [Online]. Available: https://www.scien.cx/2007/12/23/problems-with-looping-through-window-setinterval/. [Accessed: ]
rf:citation
» Problems with Looping through window.setInterval | Zach Leatherman | Sciencx | https://www.scien.cx/2007/12/23/problems-with-looping-through-window-setinterval/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.