我目前正在制作一个动画,我不得不使用setTimeout
来制作动画。
这是我的"暂停"按钮的html,该按钮在单击时更改为恢复:
<button type="button" id="pause">Pause</button>
这是我的 JavaScript 代码,我使用 js 的clearTimeout
和clearInterval
函数暂停动画。
document.getElementById("pause".addEventListener("click",function(){
toggleText();
clearTimeout(yT);
clearTimeout(gT);
clearTimeout(yTt);
clearTimeout(rsT);
clearInterval(sI);
我想从暂停的那个点恢复动画。我尝试了这个社区中 Mr.Tim 的其他帖子中建议的一些功能,但到目前为止没有任何效果。
Kiran链接了另一个问题,这对你来说可能是一个很好的解决方案。
如前所述,没有内置的pauseTimeout
函数。
但是,更简单的方法是在您的setTimeout
中使用 if 语句。像这样:
let timeoutPaused = false;
setTimeout(function(){
if (!timeoutPaused) {
doSomething();
}
}, 1000)
function toggleTimeout() {
timeoutPaused = !timeoutPaused;
}
然后,您可以在要关闭或打开它时拨打toggleTimeout
。另外,您甚至不需要将其作为单独的功能,我只是出于教育目的而这样说。