DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • 5 Best Node.js Practices to Develop Scalable and Robust Applications
  • Concurrency and Parallelism in Node.js for Scalable Apps
  • Streamline Microservices Development With Dapr and Amazon EKS

Trending

  • How To Replicate Oracle Data to BigQuery With Google Cloud Datastream
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • How to Convert Between PDF and TIFF in Java
  • Setting Up Data Pipelines With Snowflake Dynamic Tables
  1. DZone
  2. Coding
  3. JavaScript
  4. Working With Timers in Node.js

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.

By 
Jawad Hasan Shani user avatar
Jawad Hasan Shani
DZone Core CORE ·
Jun. 11, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.8K Views

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. 

In this post, I will describe and demonstrate what timers are, how to use them, what the syntax looks like, and then how you can leverage them in your applications. One common example, if you want to retrieve data from a REST API on specific interval, you can achieve very easily using timers. So, even if you are new to JavaScript or timers, this post will help you understand these concepts. If you are interested in knowing more about Node, you can also check my other articles as well. 

Timers

Timers are very popular global functions in browsers environment:

  • setTimeout.
  • setInterval.

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.

setTimeout example code block

Here is the variation of the same code, where the function is not passed in-line. 

setTimeout example code block

The next screenshot shows another variation, which shows how to pass arguments to function reference. 

setTimeout example code block

So, all the above mentioned examples are very simple and shows you various styles of setting up a setTimeout function.

Timers Exercise

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”
  • Constraints:
    • 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).

Sample timeout exercise

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).

setInterval example code block

Canceling Timers

Another cool thing about timers is that you can cancel them with code. e.g. clearTimeout(timerId). 

clearTimeout example

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.

setInterval example

Summary

We learned that it's easy to work with timers in Node.js. The code is similar what we were using in JavaScript for browsers. They are very handy functions and can be used in various scenarios. Have you done the exercise yet, give it a try and share your solution with me. Feel free to let me know if you have some questions. Till next time, Happy coding.

Node.js

Published at DZone with permission of Jawad Hasan Shani. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • 5 Best Node.js Practices to Develop Scalable and Robust Applications
  • Concurrency and Parallelism in Node.js for Scalable Apps
  • Streamline Microservices Development With Dapr and Amazon EKS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!