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

performance - recursive function vs setInterval vs setTimeout javascript

i am using NodeJs and need call a infinite function, but i dont know what is the best for a optimal performance.

recursive function

function test(){
//my code
test();
}

setInterval

setInterval(function(){
//my code
},60);

setTimeout

function test(){
//my code
setTimeout(test,60);
}

I want the best performance without collapse the server. My code have several arithmetic operations.

appreciate any suggestions to optimize the javascript performance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Be carefull.. your first code would block JavaScript event loop.

Basically in JS is something like list of functions which should be processed. When you call setTimeout, setInterval or process.nextTick you will add given function to this list and when the right times comes, it will be processed..

Your code in the first case would never stop so it would never let another functions in the event list to be processed.

Second and third case is good.. with one little difference.

If your function takes to process for example 10ms and interval will be yours 60ms..

  • function with setInterval will be processed in times: 0-10, 60-70, 120-130, ... (so it has only 50ms delay between calls)
  • But with setTimeout it will be:
    • if you call func first: 0-10, 70-80, 140-150, 210-220, ...
    • if you call setTimeout first: 60-70, 130-140, 200-210, ...

So the difference is delay between starts of your function which can be important in some interval based systems, like games, auctions, stock market.. etc..

Good luck with your recursion :-)


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

...