Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

how many javascript setTimeout/ setInterval call can be set simultaneously in one page?

I have to use atleast 2 setTimeouts and 1 setInterval. Does this have any dependency on the browser or javascript engine being used?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

tl;dr: Don't worry about the cost of timers until you're creating 100K's of them.

I just did a quick test of timer performance by creating this test file (creates 100K timers over and over):

<script>
var n = 0; // Counter used to verify all timers fire

function makeTimers() {
  var start = Date.now();
  for (var i = 0; i < 100000; i++, n++) {
    setTimeout(hello, 5000);
  }
  console.log('Timers made in', Date.now() - start, 'msecs');
}

function hello() {
  if (--n == 0) {
    console.log('All timers fired');
    makeTimers(); // Do it again!
  }
}

setTimeout(makeTimers, 10000);  // Wait a bit before starting test
</script>

I opened this file in Google Chrome (v54) on my circa ~2014 Macbook Pro, and went to the Timeline tab in Developer Tools and recorded the memory profile as the page loaded and ran thru 3-4 cycles of the test.

Observations

The timer creation loop takes 200ms. The page heap size starts at 3.5MB pre-test, and levels out at 3.9MB.

Conclusion

Each timer takes ~.002 msecs to set up, and adds about 35 bytes to the JS heap.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...