js setInterval暂停与继续
时间: 2023-10-21 17:55:00 浏览: 115
在 JavaScript 中,`setInterval`函数是用来重复执行指定的代码片段的。要实现暂停和继续效果,你可以使用 `clearInterval` 函数来取消定时器。
下面是实现 `setInterval` 的暂停和继续的示例代码:
```javascript
var intervalId; // 用于保存 setInterval 的返回值
var isPaused = false; // 用于标记是否暂停
function startInterval() {
intervalId = setInterval(function() {
// 需要重复执行的代码
}, delay);
}
function pauseInterval() {
if (!isPaused) {
clearInterval(intervalId);
isPaused = true;
}
}
function resumeInterval() {
if (isPaused) {
startInterval();
isPaused = false;
}
}
// 开始定时器
startInterval();
// 暂停定时器
pauseInterval();
// 继续定时器
resumeInterval();
```
在上面的代码中,`startInterval` 函数用于开始定时器,`pauseInterval` 函数用于暂停定时器,`resumeInterval` 函数用于继续定时器。通过设置 `isPaused` 变量的状态来判断是否暂停,并使用 `clearInterval` 取消或重新启动定时器。