Node.js has various inbuilt methods that make managing asynchronous tasks easier compared to other server-side programming languages. The event loop is used to implement the asynchronous functionality of Node.js.
An event loop is a single-threaded semi-infinite loop that executes I/O or timer callbacks sequentially using a set of queues. The event loop has six different phases: timers, pending callbacks, idle or prepare, poll, check, and close callbacks. In this article, we’ll focus on the timers phase. We’ll look at examples for setTimeout()
, clearTimeout()
, and other Node.js timer functions.
Contents
Setting Node.js timer functions
The Node.js timer module contains functions that run code after a set amount of time. Timer methods are globally available to imitate the browser JavaScript API, hence they do not need to be imported via require()
.
Let’s explore the timer functions in Node.js:
setTimeout()
setTimeout()
can be used to set code execution after a certain period of time has passed (in milliseconds). It is similar to the JavaScript API’s window.setTimeout()
function in browsers. A string of code, on the other hand, cannot be passed to be executed.
The setTimeout()
function takes three arguments:
- First: the function to be run
- Second: the delay in milliseconds
- Third (optional): an argument to be passed to the function
Here’s an example of the setTimeout()
function:
const myTimeout = setTimeout(myGreeting, 5000, "Pascal"); function myGreeting(arg) { console.log("Welcome back " + arg) }
Because of the setTimeout
call, the function in the above example, myGreeting()
, will execute after close to 5000
milliseconds (or 5 seconds). The execution of the timeout can be slightly delayed due to other executing codes that run in the event loop.
The third parameter, Pascal
, is a string that is passed to the myGreeting()
function as its argument.
setTimeout()
returns a Timeout
object, which may be used to terminate the timeout using the clear
method known as clearTimeout()
. One real life use case of a setTimeout()
function is a countdown to a flash sale in an ecommerce app.
setInterval()
setInterval()
causes an indefinite loop to be executed. It is most useful for repeating a piece of code with a millisecond delay. SetInterval()
, like setTimeout()
, requires three arguments:
- First: the function to be executed
- Second: the delay in milliseconds
- Third (optional): an argument to be passed to the function
Here’s an example of the setInterval()
function:
function myInterval() { console.log('Catch me if you can!'); } setInterval(myInterval, 3000);
In the above example, the function, myInterval()
, will run every 3000
milliseconds (3 seconds) until it is stopped. Similar to setTimeout()
, the delay time may not be exact owing to other code operations that may occupy the event loop.
setInterval()
produces a Timeout
object that may be used to reference and adjust the previously set interval. One real life use case of the setInterval()
function is fetching the latest price of Ethereum at an interval of 60 seconds n a crypto trading app.
setImmediate()
The setImmediate()
function runs code after the current event loop cycle is completed. setImmediate()
is similar to setTimeout()
with a 0ms time delay.
To put it another way, the setImmediate()
method will execute code after each statement in the script is executed. setImmediate()
takes two arguments:
- First: the function to be executed
- Second (optional): the function’s parameter
Here’s an example of the setImmediate()
function:
console.log('before setImmediate'); const myImmediate = setImmediate((arg) => { console.log(`Hello and welcome ${arg}!`); }, 'Pascal'); console.log('After setImmediate'); for(let i=0; i<10; i++){ console.log(i); }
In the above example, the setImmediate()
function will run after all executable code has completed.
The output will be as follows:
before immediate after immediate 0 1 2 3 4 5 6 7 8 9 Hello and welcome Pascal!
If you have a long CPU-bound process that you wish to make it async so that the event loop may continue to operate and handle other requests; setImmediate()
is a decent option.
Clearing Node.js timer functions
setTimeout()
, setInterval()
, and setImmediate()
all return an object that may be used to refer to the Timeout
or Immediate
objects, respectively. Node.js provides clear
functions for stopping or canceling the execution of the Timeout
or Immediate
objects.
clearTimeout()
The clearTimeout()
function is used to cancel the Timeout
object created by the setTimeout()
function:
const myTimeout = setTimeout(myGreeting, 5000, "Pascal"); function myGreeting(arg) { console.log("Welcome back " + arg) } clearTimeout(myTimeout)
clearInterval()
The clearInterval()
function halts the interval object created by the setInterval()
function:
function myInterval() { console.log('Catch me if you can!'); } setInterval(myInterval, 3000); clearInterval(myInterval)
clearImmediate()
The clearImmediate()
function stops the immediate objected returned by the setImmediate()
function:
console.log('before setImmediate'); const myImmediate = setImmediate((arg) => { console.log(`Hello and welcome ${arg}!`); }, 'Pascal'); console.log('After setImmediate'); for(let i=0; i<10; i++){ console.log(i); } clearImmediate(myImmediate);
Other timer functions
unref()
unref()
is a Timeout
method that notifies the Timeout
object that the Node.js event loop is no longer required. Because there is no other event keeping the event loop going in this situation, it will end before the callback to setTimeout()
is executed:
const myTimeout = setTimeout(myGreeting, 5000, "Pascal"); function myGreeting(arg) { console.log("Welcome back " + arg) } // Checking the myTimeout.hasRef() object console.log(myTimeout.hasRef()); // Unreferencing console.log(myTimeout.unref());
For the example above, the output will 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()
function is not printed on the console. Notice the [Symbol(refed)]
is set to false
.
ref()
The ref()
method is called if the Timeout
object’s event loop is no longer active. The ref()
method is only used after timeout.unref()
has been called and you need to access the Timeout
object once more:
const myTimeout = setTimeout(myGreeting, 5000, "Pascal"); function myGreeting(arg) { console.log("Welcome back " + arg) } // Checking the myTimeout.hasRef() object console.log(myTimeout.hasRef()); // Unreferencing console.log(myTimeout.unref()); // Referencing again console.log(myTimeout.ref());
The output will be as follows for the above example:
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 back Pascal
The myGreeting()
function is printed on the console and you will notice the [Symbol(refed)]
is set to true
.
Conclusion
Timers are used in Node.js to execute a function at a certain time or to delay a program or code execution. In this article, we discussed the different timer functions available in Node.js to set or clear the execution of code. We looked at examples for setTimeout()
, setInterval()
, setImmediate()
, clearTimeout()
, clearInterval()
, and clearImmediate()
. We also discussed two additional timer functions: unref()
and ref()
.
The post Using <code>setTimeout()</code> and other timer APIs in Node.js appeared first on LogRocket Blog.
from LogRocket Blog https://ift.tt/qLkVrD5
Gain $200 in a week
via Read more