Home > Web Front-end > CSS Tutorial > How Can I Stop a `setTimeout` or `setInterval` Loop in JavaScript?

How Can I Stop a `setTimeout` or `setInterval` Loop in JavaScript?

Linda Hamilton
Release: 2024-12-01 16:23:09
Original
393 people have browsed it

How Can I Stop a `setTimeout` or `setInterval` Loop in JavaScript?

Stopping a setTimeout Loop

When constructing a loading indicator using a sprite, a common approach involves employing a function to set the background position of the indicator. To create a continuous loop, the code resorts to recursively invoking the function within a setTimeout callback. However, there may come a point where you need to halt this loop upon completion of a certain action.

One solution is to retrieve the timer handle returned by setTimeout and use it with clearTimeout to terminate the loop. Here's a modified version of the code that implements this approach:

function setBgPosition() {
  var c = 0, timer = 0;
  var numbers = [0, -120, -240, -360, -480, -600, -720];

  function run() {
    Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
    if (c >= numbers.length) {
      c = 0;
    }
    timer = setTimeout(run, 200);
  }

  timer = setTimeout(run, 200);
  
  return stop;  // Function to stop the loop

  function stop() {
    if (timer) {
      clearTimeout(timer);
      timer = 0;
    }
  }
}
Copy after login

To use this code, you can call setBgPosition() and store the returned function (stop) in a variable:

var stop = setBgPosition();
Copy after login

When you need to stop the loop, simply call the stop function:

stop();
Copy after login

Alternatively, you can utilize setInterval instead of setTimeout. setInterval automatically repeats the specified function at a given interval. Here's an example using setInterval:

function setBgPosition() {
  var c = 0;
  var numbers = [0, -120, -240, -360, -480, -600, -720];

  function run() {
    Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
    if (c >= numbers.length) {
      c = 0;
    }
  }
  
  return setInterval(run, 200);
}
Copy after login

In this scenario, the code below will stop the loop:

var timer = setBgPosition();
clearInterval(timer);
Copy after login

The above is the detailed content of How Can I Stop a `setTimeout` or `setInterval` Loop in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template