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.
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
orprocess.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..
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 :-)
Assuming the "perfomance delay" described by Jan Juna, I have tried this simple script to check if there are any differences in terms of throughput:
Interval:
Timeout:
And this is the output vith nodejs 8.11: that shows no difference in terms of throughput:
The recursive function cause a stack overflow. That's not what you want.
The
setInterval
andsetTimeout
ways you have shown are identical, except thatsetInterval
is more clear.I'd recommend
setInterval
. (After all, that is what it's for.)//use setInterval function
1000ms=1second; property like style.width etc;
As already mentioned, endless recursive functions lead to a stack overflow. Time triggered callbacks will be executed in an own context with a clear stack.
setInterval
is useful for more accurate periodic calls over recursivesetTimeout
, however, there is a drawback: The callback will be triggered even if an uncaught exception was thrown. This usually produces a several bytes long log entry every 60 milliseconds, 1'440'000 entries per day. Furthermore asetInterval
callback with heavy load could end up in an unresponsive script or even hole system.Recursive
setTimeout
immediate before return from function will not be executed if any exception hasn't been caught. It will guarantee a time frame for other tasks after return from the callback function independent of the function's execution time.Not sure what you're trying to accomplish, but here's a "safe" way to use recursion... https://stackoverflow.com/questions/24208676/how-to-use-recursion-in-javascript/24208677