⏰🚀Understanding setTimeout, setImmediate, process.nextTick, and setInterval in Node.js ⏳⏰👨‍💻
Tags: webdev, javascript, programming, node
Published: 2024-06-29 05:39:43

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_

```javascript
(()=>{
    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
*/
```

**setImmediate**
`setImmediate `executes 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_

```javascript
(()=>{
    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
*/
```

**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_.

```javascript
(()=>{
    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
*/
```

**setInterval**
`setInterval `is 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 `clearInterval `or it can run for infinite time_

```javascript
(()=>{
    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 
*/
```

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()](https://nodejs.org/en/learn/asynchronous-work/understanding-processnexttick)
[Understanding setImmediate()](https://nodejs.org/en/learn/asynchronous-work/understanding-setimmediate)
[Discover Javascript timers](https://nodejs.org/en/learn/asynchronous-work/discover-javascript-timers#settimeout)