Zach’s ugly mug (his face) Zach Leatherman

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. Read 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 IndieWeb Avatar for https://zachleat.com/is a builder for the web at IndieWeb Avatar for https://fontawesome.com/Font Awesome and the creator/maintainer of IndieWeb Avatar for https://www.11ty.devEleventy (11ty), an award-winning open source site generator. At one point he became entirely too fixated on web fonts. He has given 83 talks in nine different countries at events like Beyond Tellerrand, Smashing Conference, Jamstack Conf, CSSConf, and The White House. Formerly part of CloudCannon, Netlify, Filament Group, NEJS CONF, and NebraskaJS. Learn more about Zach »

2 Comments
  1. Jeff Watkins Disqus

    16 Jan 2008
    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 Disqus

    17 Jan 2008
    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.
Shamelessly plug your related post

These are webmentions via the IndieWeb and webmention.io.

Sharing on social media?

This is what will show up when you share this post on Social Media:

How did you do this? I automated my Open Graph images. (Peer behind the curtain at the test page)