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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Set Time Delay in JavaScript?
Next article icon

How to stop setInterval Call in JavaScript ?

Last Updated : 04 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, the setInterval() function is used to repeatedly execute a specified function at a fixed interval. However, there may be scenarios where we need to stop the execution of setInterval() calls dynamically. Stopping a setInterval() call in JavaScript is essential to prevent ongoing repetitive tasks and manage resource usage efficiently.

Using clearInterval method

In this approach, we are using clearInterval the interval ID returned setInterval to directly stop the repetitive task execution at any point in your code.

Example 1: Implementation to show how to stop setInterval call in JavaScript.

JavaScript
let intervalId = setInterval(() => {     console.log('Executing repetitive task...'); }, 1000);   // Stop the interval after 5 seconds setTimeout(() => {     clearInterval(intervalId);     console.log('Interval stopped after 5 seconds.'); }, 5000); 

Output:

aaa

Example 2: Implementation to show how to stop setInterval call in JavaScript using conditional check.

JavaScript
let counter = 0; let intervalId = setInterval(() => {     counter++;     console.log('Counter:', counter);     if (counter >= 5) {         clearInterval(intervalId);         console.log('Interval stopped after 5 iterations.');     } }, 1000);  

Output:

aaa


Example 3: Implementation to show how to stop setInterval call in JavaScript using .

JavaScript
let isRunning = true; let intervalId = setInterval(() => {     if (isRunning) {         console.log('Executing repetitive task...');     } else {         clearInterval(intervalId);         console.log('Interval stopped using flag.');     } }, 1000);  // Stop the interval after 5 seconds using the flag setTimeout(() => {     isRunning = false; }, 5000); 

Output:

aaa


Next Article
How to Set Time Delay in JavaScript?

M

mguru4c05q
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Set Time Delay in JavaScript?
    Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
    2 min read
  • How to stop forEach() method in JavaScript ?
    Stopping a forEach() loop seems almost like an impossible task but here are a few tricks by which we might do it. Sample example using forEach(): var sum = 0; var number = [90, 4, 22, 48]; number.forEach(myFunction); function myFunction(item) { sum += item; } console.log(sum); Tricks to stop forEach
    2 min read
  • How to set the cursor to wait in JavaScript ?
    In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its beha
    3 min read
  • How to Simulate a Click in JavaScript?
    Simulating a click in JavaScript means triggering a click event on an HTML element using code, rather than requiring manual user interaction. This technique is useful for automating actions like clicking buttons, links, or other interactive elements, enhancing web functionality, and triggering hidde
    3 min read
  • How to Wait n Seconds in JavaScript?
    Here are the various methods to wait n seconds in JavaScript 1. Using setTimeout() FunctionsetTimeout() is an asynchronous function in JavaScript that allows you to run code after a specific amount of time has passed. Since setTimeout() is a method of the window object, you can technically write it
    3 min read
  • JavaScript setTimeout() & setInterval() Method
    JavaScript SetTimeout and SetInterval are the only native function in JavaScript that is used to run code asynchronously, it means allowing the function to be executed immediately, there is no need to wait for the current execution completion, it will be for further execution. [GFGTABS] JavaScript s
    2 min read
  • How to add a delay in a JavaScript loop?
    JavaScript doesn't offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a specified number of milliseconds. Below given example illustrates how to add a delay to various loops: For loop:[GFGTABS] JavaScript for (l
    3 min read
  • Difference Between setTimeout & setInterval in JavaScript
    JavaScript has both setTimeout and setInterval functions that are used for executing code after a certain delay. However, they differ in how they handle the timing of execution. Understanding their differences is crucial for effectively managing asynchronous operations in our code which is explained
    2 min read
  • How to Detect Idle Time in JavaScript ?
    The idle time is the time that the user doesn't interact with a web page. This interaction can be either moving the mouse, clicking on the page, or using the keyboard. This time can be detected to execute certain events that may need to occur after a certain period of idle time. \ Method 1: Using Ja
    4 min read
  • How to trigger setInterval loop immediately using JavaScript ?
    This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example. Note: In this article setInterval() method will start immediately for the 1st time
    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