What is the method to stop the interval in JavaScript?

[UPDATE: I appreciate the assistance from everyone. I can see that my question received some criticism for lack of research and other factors. My apologies for any oversights, and thank you for your understanding. As a newcomer to coding and stackoverflow, I am still navigating the rules and norms.]

Why does this script not cease after displaying 'DONE' once? Is there a simple solution?

function countdown(num) {
  let n = num;
  function dec() {
    if (n > 1) {
      n--;
      console.log(n);
    } else {
      clearInterval(dec);
      console.log('DONE!');
    }
  }

  setInterval(dec, 1000);
}

Your input and guidance are appreciated!

Answer №1

To stop a countdown timer in JavaScript, you must use the clearInterval function and pass in the interval id that was returned when calling setInterval.

function countdown(num) {
  let n = num, id;
  function dec() {
    if (n > 1) {
      n--;
      console.log(n);
    } else {
      clearInterval(id);
      console.log('DONE!');
    }
  }
  
  id = setInterval(dec, 1000);
}

countdown(5)

Answer №2

Make sure to save the return value from the timer in a variable so you can use it later to clear the timer. Do not try passing the callback function as the reference for clearing.

For more information, refer to the official documentation.

function startTimer(num) {
  let timerID = null; // <-- Store the timer ID
  let count = num;
  
  function decrease() {
    if (count > 1) {
      count--;
      console.log(count);
    } else {
      clearInterval(timerID); // <-- Use the stored ID to stop
      console.log('Time's up!');
    }
  }
  
  timerID = setInterval(decrease, 1000); // <-- Save the return value
}

startTimer(10);

Answer №3

Give this a shot:

function initiateCountdown(number) {
  let count = number;
  
  function decrease() {
    if (count > 1) {
      count--;
      console.log(count);
    } else {
      stopInterval();
      console.log('COUNTDOWN COMPLETE!');
    }
  }
  
  function stopInterval() {
    clearInterval(intervalID);
  }
  
  const intervalID = setInterval(decrease, 1000);
}

Answer №4

Make sure to clear timers instead of functions

function countdown(num) {
    let n = num;
    function dec() {
        if (n > 1) {
            n--;
            console.log(n);
        } else {
            clearInterval(a);
            console.log('DONE!');
        }
    }

    const a = setInterval(dec, 1000);
}
countdown(1)

Answer №5

If you're looking to build on top of what others have already shared, the code snippet below offers a more concise solution:

const countdown = (num) => {
  const interval = setInterval(() => {
    if (num <= 1) {
      clearInterval(interval);
      console.log('Countdown Complete');
    } else {
      num--;
      console.log(num);
    }
  }, 1000);
};

countdown(10);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with $http response not appearing in AngularJS application

Currently, I am in the process of developing an angularjs application and encountering a challenging issue with setting up the $http connection to a php file. The header is displaying a response that I echoed from php. Nevertheless, two key problems persis ...

The challenge of integrating Bootstrap with Mixitup filtering on page load

Looking to showcase our portfolio in bootstrap using MixItUp v3.1.11 filtering, and attempting to load a specific category (not all projects) upon page load. Patrick Kunka has shared an example of achieving this here. A related question was asked here O ...

What is the best way to transfer variables from a JavaScript file to the tailwind.config file?

For my current project, I have decided to implement tailwind css for the first time. I understand how to define variables in tailwind-config for properties like 'colors' and 'border-radius' However, in this particular situation, The v ...

"An issue with Angular Http Get causing Status 0 to be consistently returned when using ng

I've been attempting to make this function properly. The concept is simple: click the tag, which then triggers a REST service call that returns a JSON result. I extract the country name from the response just for testing purposes. I'm currently u ...

Issue with Angular modal text boxes failing to populate using ngModel

I am facing an issue with populating data in a modal when a table row is clicked. The table contains TV show data and uses dir-paginate/ng-repeat to display the information. However, when I click on a row to edit the show, the ng-model data does not load i ...

Encountering issues when attempting to retrieve localized images within .vue files using a custom webpack configuration

Currently, I am deep into learning webpack and attempting to craft my own vue template. However, I have encountered an issue that does not arise in webpack-simple or other templates. Despite having a configuration for images that closely resembles what is ...

The location of errors is not displayed in VueJS stack traces

My Current VueJS Setup Check out the Source Code here I am working on a project using VueJS with webpack. I have chosen not to use the vue-loader plugin or .vue files. My project structure resembles a typical Javascript webpack project where I import vu ...

The Passport.js local strategy with a unique twist on identification parameters

I am currently in the process of implementing a local authentication strategy for my web application, but I have encountered some difficulties with my approach. While reviewing Passport's documentation and various examples, I noticed that there is no ...

Combining the MergeMap and Map operators in RxJS using Typescript

Struggling to grasp the concept of RxJS, I am currently learning and trying to understand this code snippet: mapOfPeople = new Map<number, any>(); const people = [ { name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: ...

Guide on altering the background color of a table row depending on the data in its cells with the help of AngularJS

I am looking to dynamically change the background color of a row based on specific cell data. If the first four characters in a table cell match a certain value, I want the entire row to change its color to red. Currently, my code changes the row color ba ...

How can client-side routing be effectively utilized?

I have a question about the utilization of AngularJS and Node.js in my web application. I have implemented client-side routing using routeProvider to navigate within different pages. All data is retrieved from a RESTful API server-side. However, most of ...

Developed a toggleable card component using the useState hook within a list, resulting in all items being toggled simultaneously

Check out this code snippet: import { useState, useEffect } from 'react' export default function AdminsComponent() { const [isActive, setIsActive] = useState(false) const toggleSetActive = () => { setIsActive(!isActive) } const ...

Maximize the YouTube video for full screen viewing

Take a look at the code snippet from our page here: <div className={styles.videoPreview}> <iframe src={`${videoData[router.locale]}?autoplay=0`} title="Flytime" ...

Clear radio button selection in Angular

Looking to refresh radio button selection in AngularJS. I have a group of three radio buttons that reveal different content based on the selected option, with a default value set to display the first radio button upon loading the app. function resetRadi ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

The JSON syntax contains an unexpected token

I am encountering an issue with a JavaScript variable named "text" that contains the following value: text={"text":"@RT #Olle_Carly Nuevas filtraciones del iPhone 6: así sería comparado con el Samsung Galaxy S5 y el iPhone 5S: Des... http://t.co/eRuXLS6 ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

This code is only functional on JSFiddle platform

I encountered an issue with my code recently. It seems to only work properly when tested on jsfiddle, and I can't figure out why it's not functioning correctly on codepen or when run from local files. Why is this code specific to jsfiddle? When ...

Can the parameters in a .slice() be customized within a v-for loop?

I am currently working with Laravel 8 and using blade syntax. The following code snippet is from a Vue component I created: <li class="w-3/12 md:w-auto pt-0 md:px-4 md:pt-2 md:pb-0 list-none relative" v-if="comic.item_type === 'b&ap ...

Unable to update data from false to true in vue.js

What I'm trying to do is change the data from false to true in order to conditionally render a button when a payment has succeeded. When making an axios call, I receive 'succeeded' as the response in the JSON object and can log it to the con ...