Working With Timers in Node.js
In this post, we will see what timers are in general and how we can use timers in our Node.js applications.
Join the DZone community and get the full member experience.Join For Free
Timers are polyglot. They are very useful in many use cases. Almost all major programming languages supports them, and Node.js is no exception. It's actually more simple in Node because Node lets us reuse our existing learning of timers.
Timers are very popular global functions in browsers environment:
Node.js has an API for these functions as well, and it exactly matches the browser’s API.
These functions can be used to delay or repeat the execution of other functions, which they receive as argument.
Timers Example(s) – setTimeout
This code uses
setTimeout to delay execution of a function by 4 seconds. Note that function passed as an argument is a function references. It might not be an inline function.
Here is the variation of the same code, where the function is not passed in-line.
The next screenshot shows another variation, which shows how to pass arguments to function reference.
So, all the above mentioned examples are very simple and shows you various styles of setting up a
Here is an exercise for you to try. If you like, you can share your solution in the comments section. Also if interested, let me know and I will share my solution as well. So, here is the description for the exercise.
- Print the following (after their corresponding delays):
- “Hello after 4 seconds”
- “Hello after 8 seconds”
- Define only a single function in your script which includes inline function(s). Hint: It might look something like below (again use your own way to achieve this and as you like).
Timers Example(s) - setInterval
We can use setInterval if we want to repeat some action on time. The following example will printing to console after 3 seconds interval, forever (unless we stop it).
Another cool thing about timers is that you can cancel them with code. e.g. clearTimeout(timerId).
Instead of clearTimeout you can use SetImmediate for same result. but this is less common.
If you are using setInterval, you can use clearInterval function to cancel that as well. The following example demonstrate that.
Published at DZone with permission of Jawad Hasan Shani. See the original article here.
Opinions expressed by DZone contributors are their own.
Security Challenges for Microservice Applications in Multi-Cloud Environments
Working on an Unfamiliar Codebase
Building and Deploying Microservices With Spring Boot and Docker
Tomorrow’s Cloud Today: Unpacking the Future of Cloud Computing