Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Fermentum Dui Faucibus Bnornare Quam Viverra Orci

    React

    Build Real-World React Native App #8 : implement Dark mode

    JavaScript

    React Lesson 5: React Devtools and Reusable Open-Source Components

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / JavaScript / Node.js / Node.js Lessons / Node.js Lesson 17: Timers, Differences from Browser, ref and ref
    Node.js

    Node.js Lesson 17: Timers, Differences from Browser, ref and ref

    Mohammad Shad MirzaBy Mohammad Shad MirzaMarch 9, 2021Updated:March 9, 2021No Comments6 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Node.js Lesson 17: Timers, Differences from Browser, ref and ref
    Node.js Lesson 17: Timers, Differences from Browser, ref and ref
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Node.js Lesson 17: Timers, Differences from Browser, ref and ref
    Node.js Lesson 17: Timers, Differences from Browser, ref and ref

    Hello everyone, this lesson will talk about different timers that we can use in Nodejs. We will also talk about what a ref is and how we can use them. Let us start.

    What are timers in Nodejs?

    Timer functions in Nodejs are similar to what we get in the browser, but there are slight differences. The browser provides us a window object which gives us the timer functions. Nodejs bundles all the functionalities in the Nodejs itself and emulates the behavior of the browser. Since Nodejs bundles this functionality out of the box, you don’t have to require anything to use it inside a project.

    We will talk about three types of timers mainly:

    1. setTimeout
    2. setInterval
    3. setImmediate

    1. Set Timeout

    Set timeout allows us to run a piece of code after a certain amount of time. We pass this ‘piece of code’ as a callback function in the first argument. While the second argument receives a number, this number denotes milliseconds, after which the callback gets called.

    setTimeout(function () {
        console.log('5 seconds have passed');
    }, 5000);

    If we see the above code, the callback function logs a statement after 5 seconds since we passed 5000 as the second argument. While this looks very similar to what happens on the web, it’s not.

    Nodejs used Event Loop to queue async callback and only calls the pending callback once the current execution completes and the call stack is empty. You can read the previous article, which covers Event Loop and Call Stack, in detail. Because of this non-blocking async behavior of Nodejs, we can’t guarantee that the callback will run after exact 5 seconds.

    Yes, it will be approx 5 seconds. Still, the actual time will depend upon the callbacks present in the queue during the time of execution. Any callback that comes can push back the setTimeout call further away, which can delay execution time. Let’s look at this example:

    console.log('Before timeout');
    
    setTimeout(function () {
        console.log('Set timeout over');
    }, 0);
    
    console.log('After timeout');

    What do you think will be logged by the above code? The Set timeout over log will come last even though the wait time is 0 seconds. The reason is the same as what we talked about in the above para. Any asynchronous callback is handled by Event Loop, which runs the callback when the current stack is empty, i.e., the other two logs are printed. This is why the timeout duration is not guaranteed to be accurate in Nodejs.

    Read More:  5 Essential SEO Tips for Web Developers

    2. Set Interval

    I hope you understood the set timeout we just discussed above. A set interval is pretty similar to that, but instead of running the function once after the timeout, it runs it again and again until you stop it. Let’s see an example:

    setInterval(function () {
        console.log('1 second has passed');
    }, 1000);

    The above code will print the log every second throughout the process lifecycle unless we stop it ourselves. Now when to use it?

    Suppose you are building a countdown where you have to show count each second; setInterval will be very handy in this situation.

    We will learn about how to stop it in a while, but first, let’s look at the third timer function.

    3. Set Immediate

    Remember how we differentiated the timer functions of Node from the one present in the browser? Every callback passes to setTimeout goes to the Event Loop and call stack before it gets executed. Set Immediate helps us in that situation. It is very similar to setTimeout with 0ms timeout but not so much. Let’s see how:

    console.log('Before timeout');
    
    setTimeout(function () {
        console.log('Set timeout over');
    }, 0);
    
    setImmediate(function () {
        console.log('Run Immediate call'); // look this closely
    });
    
    console.log('After set immediate');

    I’ll share the log to explain what’s happening:

    Before timeout
    After set immediate
    Set timeout over
    Run Immediate call

    Any function passed as the setImmediate() argument is a callback executed in the next iteration of the event loop. When we execute the above code, setTimeout will enter the loop and then setImmediate(). Since we said that setImmediate would run in the next iteration, it gets executed after the timeout. Let’s see one more example:

    console.log('Before timeout');
    
    setTimeout(function () {
        console.log('Set timeout over');
    }, 0);
    
    setImmediate(function () {
        console.log('Run Immediate call'); // look this closely
    });
    
    setTimeout(function () {
        console.log('Another timeout over');
    }, 0);
    
    console.log('After set immediate');
    
    // logs 
    // Before timeout
    // After set immediate
    // Set timeout over
    // Another timeout over
    // Run Immediate call

    Even though setImmediate enter the loop in the second position, it gets executed last. This is what we meant when we read “callback that’s executed in the next iteration of the event loop”.

    Read More:  Overview of Basic Data Structures: How to Organize Data the Efficient Way

    So when to use it? You can use setImmediate() whenever you want to queue a callback after everything in the callback is executed. Consider it as saying, “Run this callback when you’re done with all the I/O or async work.”

    Now that we understand all three types of the timer and how to start them. Let’s look at how to stop them.

    How to stop timer functions

    All the timers we talked about scheduling some action to be executed in the future. So we should also learn to cancel that future execution if we want to. For this, we will have to understand ‘ refs’.

    Whenever you create a timer, it returns a reference to the timer we can use to update its behavior. Consider this reference as a unique ID that lets us get a hand on the timer. Let’s see the code below:

    const interval = setInterval(() => {
        console.log('tik');
    }, 1000);
    
    setTimeout(() => {
        clearInterval(interval);
    }, 4000);
    
    // logs
    // tik
    // tik
    // tik

    The above code creates an interval that prints ‘tik’ every second. We are storing the reference to a variable ‘ref.’

    Then pass that ref to a function clearInterval() after 4 seconds. Since the interval was canceled at the 4th second, we see only 3 logs of ‘tik.’

    Similarly, we get functions to clear the 3 timers respectively. They are:

    1. clearTimeout()
    2. clearInterval()
    3. clearImmediate()

    The usage is similar in all 3 cases. You store a ref in a variable then pass it to the clear function to cancel the execution.

    By default, Nodejs keeps the event loop running as long as the timer is active. This lets the timer be executed in the future and keeps the process from exiting. interval.ref() and interval.unref() functions that can control this default behavior.

    timeout.ref() or interval.ref() will keep the event loop active as long as the timer is active. It is always called by default, so it’s not needed to be called again.

    timeout.unref() or interval.unref() will prevent the timer to be active if there is no event loop activity in progress. This will prevent side effects from happening. Process exiting while a timer is active will have no side effect.

    The source code of the lesson you can find by the link.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Mohammad Shad Mirza
    • X (Twitter)
    • LinkedIn

    JavaScript lover working on React Native and committed to simplifying code for beginners. Apart from coding and blogging, I like spending my time sketching or writing with a cup of tea.

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Development November 27, 2024

    Top Front-End Development Tools to Elevate Your Projects in 2024

    As front-end development continues to evolve, leveraging the right tools can enhance project efficiency and innovation. In 2024, top tools like React, Vue.js, and Figma are vital for creating responsive, user-centric applications that drive success.

    UX Engineers and the Skills They Need

    November 22, 2019

    Implementing a BackgroundRunner with Flask-Executor

    March 22, 2023

    Dockerizing Django with Postgres, Redis and Celery

    December 31, 2020

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Важность учета рабочего времени

    Wiki June 25, 2016

    Developer Guide to GDPR

    Beginners August 29, 2019

    Sending Emails in Java Applications: A Comprehensive Guide to JavaMail and SMTP Configuration

    Java January 9, 2024

    Mastering LinkedIn Lead Generation: Strategies for Success

    LinkedIn November 30, 2024

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Programming

    Full Node.js Course

    JavaScript

    Implementing Role-Based Access Control in a Node.js application

    Beginners

    5 Website Security Threats and How to Counter Them

    Most Popular

    Working With API in React Application using Axios and Fetch

    JavaScript

    Основные принципы и правила нашей команды

    Wiki

    23. Уроки Node.js. Домены, “асинхронный try..catch”. Часть 3.

    Programming
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.