Search code examples
javascriptperformancesetintervaluser-experience

For the performance is better two functions in the same setInterval() or two different setInterval ? - Javascript


For the performance is better two functions in the same setInterval() or each function in different setInterval() ?

A

setInterval(function(){ 
 one();
 two(); 
}, 60000);

function one(){
 //code
}

function two(){
 //code
}

B

setInterval(function(){ 
 one();     
}, 60000);

setInterval(function(){      
 two(); 
}, 60000);

function one(){
 //code
}

function two(){
 //code
}

What do you suggest ? Thanks a lot...


Solution

  • For the performance is better two functions in the same setInterval() or each function in different setInterval() ?

    There are few points of view on performance.

    From the performance of those two functions, it is faster to call setInterval() just once, it is faster to call function one() then two() from the context of anonymous function rather then from timing event context. And it is also worth mentioning, that those two functions might be inlined/merged together with a JS compiler or JS JIT.

    From the user experience point of view, it better to split long functions into two, so user interface events get processed in between those functions. In other words:

    1. Process user events (say, mouse clicks).
    2. Call long function one().
    3. Process user events again.
    4. Call long function two().
    5. Process user events.

    will be much better for user experience than:

    1. Process user events.
    2. Call huge combined function one() and two(), hanging browser for a noticeable period.
    3. Process user events.

    And the last point. From the overall performance of the program, it does not matter at all, since the interval between those calls so long, so it does not make any difference for the overall performance.