How to pause and resume jquery interval

前端 未结 3 888
粉色の甜心
粉色の甜心 2021-01-24 23:32

I have made a custom slider with jQuery. For this I have used setInterval function:

timer = setInterval(function() {},  8000);

But I cannot pau

3条回答
  •  -上瘾入骨i
    2021-01-24 23:59

    there are two ways of accomplish this:

    1. Clearing the interval everytime you pause and starting a new interval when you resume it.

    2. Having a flag to tell the function in the interval when it is paused and it should not do anything.

    The first solution would work like this:

    var intervalId = false;
    
    function intervalFunction () {
       // do stuff.
    }
    
    startButton.onclick = function () {
        if (intervalId === false) {
            intervalId = setInterval(intervalFunction, 8000);
        }
    }
    
    pauseButton.onclick = function () {
        if (intervalId !== false) {
            clearInterval(intervalFunction);
            intervalId = false;
        }
    }
    
    // auto start it:
    intervalId = setInterval(intervalId);
    

    The second solution would work like this:

    var isRunning = true;
    var interval = setInterval(function() {
        if (!isRunning) {
            // not running, do nothing
        } else {
            // it is running, do stuff.
        }
    }, 8000);
    
    pauseButton.onclick = function () {
        isRunning = false;
    };
    startButton.onclick = function () {
        isRunning = true;
    };
    

提交回复
热议问题