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
370 views
in Technique[技术] by (71.8m points)

javascript - Recursive function call with setTimeout limited to ~200 calls per second, why?

This code recursively calls the same function with a setTimeout of 1 millisecond, which in theory should call the function 1000 times per second. However, it's only called about 200 times per second:

This behavior happens on different machines and different browsers, I checked if it's has something to do with the maximum call stack, but this limit is actually way higher than 200 on any browser.

const info = document.querySelector("#info");
let start = performance.now();
let iterations = 0;

function run() {  
  if (performance.now() - start > 1000) {
    info.innerText = `${iterations} function calls per second`;
    start = performance.now();
    iterations = 0;
  }
  
  iterations++;
  setTimeout(run, 1);
}

run();
<div id="info"></div>
question from:https://stackoverflow.com/questions/65672101/recursive-function-call-with-settimeout-limited-to-200-calls-per-second-why

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

1 Reply

0 votes
by (71.8m points)

There’s a limitation of how often nested timers can run. The HTML5 standard says: 11: "If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4."

This is true only for client-side engines (browsers). In Node.JS this limitation does not exist

HTML Standard Timers Section
Very similar example from javascript.info


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

...