如何停止setInterval并继续?

时间:2019-06-01 18:39:31

标签: javascript setinterval

如何停止setInterval,然后从同一位置恢复?

示例:

UniqueProductChecker

index.html

Product

index.js

start ---> 1,2,3,4,5 .... ---> stop ---> start ---> 6,7,8 ...

2 个答案:

答案 0 :(得分:5)

您需要一个全局变量i并用于停止clearInterval

function start() {
    if (refreshInterval !== undefined) return; // prevent more than one interval
    refreshInterval = setInterval(function() {
        console.log(i);
        i++;
    }, 1000);
}

function stop() {
    clearInterval(refreshInterval);
    refreshInterval = undefined;
}

var refreshInterval,
    i = 0;
<div onclick="start()">start</div>
<div onclick="stop()">stop</div> 

答案 1 :(得分:1)

您可以将count变量保留在外部作用域中,这样就不会在每次运行start函数时都将其重置

let refreshInterval = null;
let count = 0

function start() {
    refreshInterval = setInterval(function() {
      document.getElementById('value').innerText = count
      count++;
    }, 1000);
    document.getElementById('start').disabled=true
}


function stop() {
    clearInterval(refreshInterval)
    document.getElementById('start').disabled=false
}
#counter{
  padding: 0.25rem;
  font-size: 1.25rem;
  border: 1px solid black;
  margin-bottom: 1rem;
}
<div  id='counter'><span>counter:</span>
<span id='value'/>0</div>
<button onclick=start() id='start'>start</button>
<button onclick=stop() id='stop'>stop</button>