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
Linda HamiltonOriginal
2024-12-01 16:23:09307browse

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;
    }
  }
}

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

var stop = setBgPosition();

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

stop();

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);
}

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

var timer = setBgPosition();
clearInterval(timer);

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:
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