Home > Web Front-end > CSS Tutorial > How to Stop a setTimeout or setInterval Loop for Loading Indicators?

How to Stop a setTimeout or setInterval Loop for Loading Indicators?

Linda Hamilton
Release: 2024-12-03 03:05:11
Original
1047 people have browsed it

How to Stop a setTimeout or setInterval Loop for Loading Indicators?

Stopping setTimeout Loops

When creating a loading indicator using a sprite, it's common to rely on a loop to cycle through background positions. One approach involves using the setTimeout function, but what if you need to stop the loop when the loading process completes?

setTimeout Implementation

The setTimeout function in JavaScript returns a timer handle that allows you to cancel the timeout using the clearTimeout function. To implement this, you can create a stop() function within the setBgPosition function:

function setBgPosition() {
    var c = 0,
        timer = 0;
    ...
    return stop;

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

To use this, you can assign the setBgPosition function to a variable and call the stop() function later to halt the loop:

var stop = setBgPosition();
// ... later ...
stop();
Copy after login

Alternative Approach: setInterval

An alternative to using setTimeout is setInterval, which repeatedly executes a function at a specified interval. Here's how you can use it with clearInterval:

function setBgPosition() {
    ...
    return setInterval(run, 200);
}
Copy after login

To stop the loop:

var timer = setBgPosition();
// ... later ...
clearInterval(timer);
Copy after login

However, it's recommended to explore options for detecting the completion condition and allowing setBgPosition to stop the loop itself. This approach provides greater control and flexibility in handling loading operations.

The above is the detailed content of How to Stop a setTimeout or setInterval Loop for Loading Indicators?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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