Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
What is the use of delay() method in jQuery ?
Next article icon

What is the use of setInterval() method in Node.js ?

Last Updated : 30 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

The setInterval() method helps us to repeatedly execute a function after a fixed delay. It returns a unique interval ID which can later be used by the clearInterval() method which stops further repeated execution of the function. 

Syntax:

const intervalId = setInterval(func,       [delay, arg1, agr2, ..., argN]);

where,

  • func is the function that we want to execute repeatedly after delay milliseconds.
  • delay (optional parameter) is the number of milliseconds delay between two repeated execution of the function.
  • arg1, ..., argN (optional parameter) are the arguments that will be passed to func when it is executed.

Example 1: In this example, we will see Infinite number of function executions.

When we use the setInterval() method and do not clear it using the clearInterval() method then it keeps on executing the function passed to it a limitless number of times. We can use the setInterval() method like this when we need to fetch some information after every fixed interval like when we are building a clock and we need to calculate and update the number of seconds after every second. A simple code example demonstrating this type of use of setInterval() method is mentioned below.

Index.js
setInterval(() => {   console.log('HELLO GEEK'); }, 1000); 

Output:

Example 2: In this example, we will see Finite number of executions using clearInterval(). If we want the function to execute a limited number of times then we can use clearInterval() method. We can clear an interval by passing the interval id that is returned from the setInterval() method to clearInterval() method.

Syntax:

clearInterval(intervalId)

The code example mentioned below demonstrates the use of clearInterval() method to attain finite repeated executions of the function.

Index.js
let count = 0;  const intervalId = setInterval(() => {   console.log('HELLO GEEK');   count++;    if (count === 5) {     console.log('Clearing the interval id after 5 executions');     clearInterval(intervalId);   } }, 1000); 

Output:

Example 3: In this example, we will see Using the arguments passed to setInterval(). The arguments that are passed to the setInterval() method after the delay parameter are received by our function and can be used in the desired manner. The code mentioned below demonstrates it with the help of a simple code example.

Index.js
let count = 0;  // The arguments passed after the  // delay (in milliseconds) will // be received in our function  // inside the setInterval() method const intervalId = setInterval(   (a, b) => {     console.log(`The sum of ${a} and ${b} is ${a + b}`);     count++;      if (count === 5) {       console.log("Clearing the interval id after 5 executions");       clearInterval(intervalId);     }   },   1000,   5,   10 ); 

Output: 


Next Article
What is the use of delay() method in jQuery ?
author
shivamsingh00141
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Node.js-Methods
  • NodeJS-Questions

Similar Reads

  • Describe the use of Timer methods in Node.js
    In this article, we are going to explore timers in Node.js and how to use them in various scenarios. The timers method in node.js contains different types of functions that are used for executing a block of code or a function at a specific period of time. It is a global module that is not required t
    3 min read
  • What is the use of delay() method in jQuery ?
    In this article, we will see how to use the delay() method and why to use it in jQuery. The delay() method is used to set a timer to delay the execution of the next item in the queue. Syntax: $(selector).delay(para1, para2); In the below example, first, we create a div of size 250px X 200px and set
    1 min read
  • What is the purpose of module.exports in node.js ?
    The module.exports is actually a property of the module object in node.js. module. Exports is the object that is returned to the require() call. By module.exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() meth
    3 min read
  • Node.js stream.finished() Method
    The stream.finished() method is utilized to receive an alert if a stream is not writable or readable anymore or if it had experienced an error or a close event that is immature. Syntax:   stream.finished(stream, options, callback) Parameters: This method accepts three parameters as mentioned above a
    3 min read
  • Node.js socket.setTTL() Method
    The socket.setTTL() method is an inbuilt application programming interface of class Socket within dgram module which is used to set or clear the IP_TTL socket option which helps to specify how many IP hops that a packet is allowed to travel through the specified router or gateway. Syntax: const sock
    2 min read
  • What is the purpose of the process object in Node JS ?
    In NodeJS, the process object is a global object that provides access to information and control over the current NodeJS process. It offers various properties and methods to interact with the underlying operating system environment and manage the NodeJS process effectively. Let's explore the primary
    2 min read
  • What is Reactor Pattern in Node.js ?
    Reactor Pattern is used to avoid the blocking of the Input/Output operations. It provides us with a handler that is associated with I/O operations. When the I/O requests are to be generated, they get submitted to a demultiplexer, which handles concurrency in avoiding the blocking of the I/O mode and
    3 min read
  • What is Express-rate-limit in Node.js ?
    express-rate-limit is a middleware for Express.js applications that helps control the rate at which requests can be made to the server. It is particularly useful for preventing abuse by limiting the number of requests a client can make to your API within a specific time frame. This can help mitigate
    3 min read
  • How To Use setInterval() Method Inside React Components?
    The setInterval() method executes a function repeatedly at a specified interval. We can use the setInterval method in a React component to update the component's state or perform other actions. Syntax: setInterval(callback, delay);callback: The function you want to run periodically.delay: The time i
    3 min read
  • Node.js socket.setBroadcast() Method
    The socket.setBroadcast() method is an inbuilt application programming interface of class Socket within dgram module which is used to set or clear the SO_BROADCAST socket option which helps the client in sending the datagram to a particular broadcast address. Syntax: const socket.setBroadcast( flag
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences