Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...