Zach’s ugly mug (his face) Zach Leat­herman

Problems with Looping through window.setInterval

December 23, 2007

Warning

This article is old and may contain information that is outdated, irrelevant, or—dare I say it—no longer accurate. Links may have rotted. Read and hyperlink with care!

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.

Zach Leatherman is a builder for the web at Font Awesome and the creator of Build Awesome (née Eleventy/11ty), an award-winning open source website generator. He measures website performance with speedlify and at one point became too fixated on web fonts. He has given 86 talks in nine different countries at events like Beyond Tellerrand, Smashing Conference, Jamstack Conf, CSSConf, and The White House. Learn more about Zach »