Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 981
J261 Avatar asked Apr 20 '14 03:04

J261


People also ask

What is the difference between setTimeout and setInterval in JavaScript?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

Is setTimeout recursive?

To repeat a function indefinitely, setTimeout can be called recursively: function repeatingFunc() { console. log("It's been 5 seconds. Execute the function again."); setTimeout(repeatingFunc, 5000); } setTimeout(repeatingFunc, 5000);

Is setInterval recursive?

setInterval function is similar to recursive setTimeout but it's different. Let's see the difference in the same example. Its interval is about 1 second as it's specified because its timer starts once setInterval is called and its timer keeps running. The callback function is triggered every second.

Is it good to use setInterval in JavaScript?

In order to understand why setInterval is evil we need to keep in mind a fact that javascript is essentially single threaded, meaning it will not perform more than one operation at a time.


1 Answers

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 :-)

like image 165
Jan Jůna Avatar answered Sep 28 '22 05:09

Jan Jůna