Tuesday, November 8, 2022
HomeWeb DevelopmentUtilizing setTimeout() and different timer APIs in Node.js

Utilizing setTimeout() and different timer APIs in Node.js


Node.js has varied inbuilt strategies that make managing asynchronous duties simpler in comparison with different server-side programming languages. The occasion loop is used to implement the asynchronous performance of Node.js.

An occasion loop is a single-threaded semi-infinite loop that executes I/O or timer callbacks sequentially utilizing a set of queues. The occasion loop has six completely different phases: timers, pending callbacks, idle or put together, ballot, examine, and shut callbacks. On this article, we’ll give attention to the timers part. We’ll have a look at examples for setTimeout(), clearTimeout(), and different Node.js timer features.

Contents

Setting Node.js timer features

The Node.js timer module accommodates features that run code after a set period of time. Timer strategies are globally obtainable to mimic the browser JavaScript API, therefore they don’t have to be imported by way of require().

Let’s discover the timer features in Node.js:

setTimeout()

setTimeout() can be utilized to set code execution after a sure time frame has handed (in milliseconds). It’s much like the JavaScript API’s window.setTimeout() perform in browsers. A string of code, alternatively, can’t be handed to be executed.

The setTimeout() perform takes three arguments:

  • First: the perform to be run
  • Second: the delay in milliseconds
  • Third (non-compulsory): an argument to be handed to the perform

Right here’s an instance of the setTimeout() perform:

const myTimeout = setTimeout(myGreeting, 5000, "Pascal");
perform myGreeting(arg) {
  console.log("Welcome again " + arg)
}

Due to the setTimeout name, the perform within the above instance, myGreeting(), will execute after near 5000 milliseconds (or 5 seconds). The execution of the timeout might be barely delayed because of different executing codes that run within the occasion loop.

The third parameter, Pascal, is a string that’s handed to the myGreeting() perform as its argument.

setTimeout() returns a Timeout object, which can be used to terminate the timeout utilizing the clear methodology often known as clearTimeout(). One actual life use case of a setTimeout() perform is a countdown to a flash sale in an ecommerce app.

setInterval()

setInterval() causes an indefinite loop to be executed. It’s most helpful for repeating a bit of code with a millisecond delay. SetInterval(), like setTimeout(), requires three arguments:

  • First: the perform to be executed
  • Second: the delay in milliseconds
  • Third (non-compulsory): an argument to be handed to the perform

Right here’s an instance of the setInterval() perform:

perform myInterval() {
  console.log('Catch me in the event you can!');
}
setInterval(myInterval, 3000);

Within the above instance, the perform, myInterval(), will run each 3000 milliseconds (3 seconds) till it’s stopped. Just like setTimeout(), the delay time is probably not actual owing to different code operations which will occupy the occasion loop.

setInterval() produces a Timeout object which may be used to reference and regulate the beforehand set interval. One actual life use case of the setInterval() perform is fetching the most recent value of Ethereum at an interval of 60 seconds n a crypto buying and selling app.

setImmediate()

The setImmediate() perform runs code after the present occasion loop cycle is accomplished. setImmediate() is much like setTimeout() with a 0ms time delay.

To place it one other method, the setImmediate() methodology will execute code after every assertion within the script is executed. setImmediate() takes two arguments:

  • First: the perform to be executed
  • Second (non-compulsory): the perform’s parameter

Right here’s an instance of the setImmediate() perform:

console.log('earlier than setImmediate');

const myImmediate = setImmediate((arg) => {
  console.log(`Whats up and welcome ${arg}!`);
}, 'Pascal');
console.log('After setImmediate');

for(let i=0; i<10; i++){
  console.log(i);
}

Within the above instance, the setImmediate() perform will run in any case executable code has accomplished.

The output might be as follows:

earlier than instant
after instant
0
1
2
3
4
5
6
7
8
9
Whats up and welcome Pascal!

You probably have an extended CPU-bound course of that you just want to make it async in order that the occasion loop might proceed to function and deal with different requests; setImmediate() is a good choice.

Clearing Node.js timer features

setTimeout(), setInterval(), and setImmediate() all return an object which may be used to consult with the Timeout or Speedy objects, respectively. Node.js gives clear features for stopping or canceling the execution of the Timeout or Speedy objects.

clearTimeout()

The clearTimeout() perform is used to cancel the Timeoutobject created by the setTimeout() perform:

const myTimeout = setTimeout(myGreeting, 5000, "Pascal");
perform myGreeting(arg) {
  console.log("Welcome again " + arg)
}

clearTimeout(myTimeout)

clearInterval()

The clearInterval() perform halts the interval object created by the setInterval() perform:

perform myInterval() {
  console.log('Catch me in the event you can!');
}
setInterval(myInterval, 3000);

clearInterval(myInterval)

clearImmediate()

The clearImmediate() perform stops the instant objected returned by the setImmediate() perform:

console.log('earlier than setImmediate');

const myImmediate = setImmediate((arg) => {
  console.log(`Whats up and welcome ${arg}!`);
}, 'Pascal');
console.log('After setImmediate');

for(let i=0; i<10; i++){
  console.log(i);
}

clearImmediate(myImmediate);

Different timer features

unref()

unref() is a Timeout methodology that notifies the Timeout object that the Node.js occasion loop is not required. As a result of there is no such thing as a different occasion retaining the occasion loop going on this state of affairs, it is going to finish earlier than the callback to setTimeout() is executed:

const myTimeout = setTimeout(myGreeting, 5000, "Pascal");
perform myGreeting(arg) {
  console.log("Welcome again " + arg)
}

// Checking the myTimeout.hasRef() object
console.log(myTimeout.hasRef());

// Unreferencing
console.log(myTimeout.unref());

For the instance above, the output might be as follows:

true
Timeout {
  _idleTimeout: 5000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 68,
  _onTimeout: [Function: myGreeting],
  _timerArgs: [Array],
  _repeat: null,
  _destroyed: false,
  [Symbol(refed)]: false,
  [Symbol(kHasPrimitive)]: false,
  [Symbol(asyncId)]: 2,
  [Symbol(triggerId)]: 1
}

The myGreeting() perform just isn’t printed on the console. Discover the [Symbol(refed)] is ready to false.

ref()

The ref() methodology known as if the Timeout object’s occasion loop is not lively. The ref() methodology is just used after timeout.unref() has been referred to as and it is advisable entry the Timeoutobject as soon as extra:

const myTimeout = setTimeout(myGreeting, 5000, "Pascal");
perform myGreeting(arg) {
  console.log("Welcome again " + arg)
}

// Checking the myTimeout.hasRef() object
console.log(myTimeout.hasRef());

// Unreferencing
console.log(myTimeout.unref());

// Referencing once more
console.log(myTimeout.ref());

The output might be as follows for the above instance:

true
Timeout {
  _idleTimeout: 5000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 73,
  _onTimeout: [Function: myGreeting],
  _timerArgs: [Array],
  _repeat: null,
  _destroyed: false,
  [Symbol(refed)]: false,
  [Symbol(kHasPrimitive)]: false,
  [Symbol(asyncId)]: 2,
  [Symbol(triggerId)]: 1
}
Timeout {
  _idleTimeout: 5000,
  _idlePrev: [TimersList],
  _idleNext: [TimersList],
  _idleStart: 73,
  _onTimeout: [Function: myGreeting],
  _timerArgs: [Array],
  _repeat: null,
  _destroyed: false,
  [Symbol(refed)]: true,
  [Symbol(kHasPrimitive)]: false,
  [Symbol(asyncId)]: 2,
  [Symbol(triggerId)]: 1
}
Welcome again Pascal

The myGreeting() perform is printed on the console and you’ll discover the [Symbol(refed)] is ready to true.

Conclusion

Timers are utilized in Node.js to execute a perform at a sure time or to delay a program or code execution. On this article, we mentioned the completely different timer features obtainable in Node.js to set or clear the execution of code. We checked out examples for setTimeout(), setInterval(), setImmediate(), clearTimeout(), clearInterval(), and clearImmediate(). We additionally mentioned two extra timer features: unref() and ref().

200’s solely Monitor failed and gradual community requests in manufacturing

Deploying a Node-based internet app or web site is the straightforward half. Ensuring your Node occasion continues to serve sources to your app is the place issues get harder. If you happen to’re focused on guaranteeing requests to the backend or third get together companies are profitable, attempt LogRocket. https://logrocket.com/signup/

LogRocket is sort of a DVR for internet and cellular apps, recording actually all the pieces that occurs whereas a person interacts together with your app. As a substitute of guessing why issues occur, you’ll be able to combination and report on problematic community requests to rapidly perceive the basis trigger.

LogRocket devices your app to report baseline efficiency timings similar to web page load time, time to first byte, gradual community requests, and in addition logs Redux, NgRx, and Vuex actions/state. .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments