⏰🚀Understanding setTimeout, setImmediate, process.nextTick, and setInterval in Node.js ⏳⏰👨‍💻

Raju Saha - Jun 29 - - Dev Community

Asynchronous programming is a core concept in Node.js, enabling it to handle I/O-bound tasks efficiently. Understanding the timing functions setTimeout, setImmediate, process.nextTick, and setInterval is crucial for writing performant and bug-free Node.js applications. In this post, we'll explore how these functions work and when to use them.

setTimeout
setTimeout() function in node.js or javascript is used
i. if you want to call it after a certain delay of time or simulate the function for a certain time.
Points to remember:
i. Minimum Delay is One milliseconds
ii. Delay are not guaranteed coz of the events loop

(()=>{
    let stockPrice=1000;
    console.log(`Stock Price: ${stockPrice}`);
    setTimeout(()=>{
        console.log(`Stock Price: ${stockPrice+10} after 5 seconds`)
    },5000)
})();

/*Output
Stock Price: 1000
Stock Price: 1010 after 5 seconds
*/
Enter fullscreen mode Exit fullscreen mode

setImmediate
setImmediateexecutes a callback on the next iteration of the event loop after the current poll phase completes.
Uses Cases:
i. to execute a function after the current I/O event callback.
ii. to ensure a function runs after an async function
Points to remember :
i. executes always after the current poll phase
ii. Not guaranteed to run before 0ms of setTimeout

(()=>{
    let stockPrice=1000;
    console.log(`Stock Price: ${stockPrice}`);
    setTimeout(()=>{
        console.log(`Stock Price: ${stockPrice+10}`)
    },0)
    setImmediate(()=>{
        console.log('Stock sales increase after increase in Price')
    })
})();

/* Output
Stock Price: 1000
Stock Price: 1010
Stock sales increase after increase in Price
*/
Enter fullscreen mode Exit fullscreen mode

process.nextTick
process.nextTick schedules a callback to be invoked in the same phase of the event loop, before the next I/O event.
Use Cases:
i. Avoiding long-running operations within a single event loop tick.
Points to remember:
i. Executes before any I/O events or timers.
ii. Can starve the event loop if used excessively.
iii. It will always execute before setTimeout and setImmediate.

(()=>{
    let stockPrice=1000;
    console.log(`Stock Price: ${stockPrice}`);
    setTimeout(()=>{
        console.log(`Stock Price: ${stockPrice+10}`)
    },0)
    setImmediate(()=>{
        console.log('Stock sales increase after increase in Price')
    })
    process.nextTick(()=>{
        console.log(`Stock Price Opening for Day: ${stockPrice+2}`)
    })
})();

/* Output
Stock Price: 1000
Stock Price Opening for Day: 1002
Stock Price: 1010
Stock sales increase after increase in Price
*/
Enter fullscreen mode Exit fullscreen mode

setInterval
setIntervalis used to run a function after a particular interval of time
Uses Cases :
i. Repeatedly executing a task at regular intervals.
ii. Creating polling mechanisms.
Points to remember:
i. Interval duration is not guaranteed.
ii. Can cause memory leaks if not cleared properly.
iii. Always use its twin function clearIntervalor it can run for infinite time

(()=>{
    let time=1;
    let stockPrice=1000;
    console.log(`Stock Price: ${stockPrice}`);
    setTimeout(()=>{
        console.log(`Stock Price Increased: ${stockPrice+10} `)
    },5000)
    let timeOut=setInterval(()=>{
        console.log(`${time++} second`)
        if(time===5){
            clearInterval(timeOut)
        }
    },1000)
})();

/* Run the above code to check the actual output
Stock Price: 1000
1 second
2 second
3 second
4 second
Stock Price Increased: 1010 
*/
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding the nuances of setTimeout, setImmediate, process.nextTick, and setInterval is key to mastering asynchronous programming in Node.js. Each function serves a specific purpose and choosing the right one can significantly impact the performance and behavior of your application. Experiment with these functions to see their effects in different scenarios and improve your asynchronous code handling.

For more information go through the below link
Understanding process.nextTick()
Understanding setImmediate()
Discover Javascript timers

. . . . . . . . . .