[英]How to resume a set timeout in JavaScript?
I am currently working on an animation where I had to use setTimeout
to animate it.我目前正在研究 animation,我必须使用
setTimeout
对其进行动画处理。
Here is my html for the button "pause" which changes to resume on click:这是我的 html 按钮“暂停”,点击后变为恢复:
<button type="button" id="pause">Pause</button>
Here is my JavaScript code where I am pausing the animation using the clearTimeout
and clearInterval
function of js.这是我的 JavaScript 代码,我正在使用 js 的
clearTimeout
和clearInterval
function 暂停 animation。
document.getElementById("pause".addEventListener("click",function(){
toggleText();
clearTimeout(yT);
clearTimeout(gT);
clearTimeout(yTt);
clearTimeout(rsT);
clearInterval(sI);
I want to resume the animation from that very point where it was paused.我想从暂停的那一刻开始恢复 animation。 I tried some functions suggested in other posts from Mr.Tim in this community but nothing is working out for me so far.
我尝试了这个社区中蒂姆先生的其他帖子中建议的一些功能,但到目前为止对我来说没有任何效果。
Kiran linked another question which is probably a good solution for you. Kiran 链接了另一个问题,这对您来说可能是一个很好的解决方案。
As mentioned, there's no built-in pauseTimeout
function.如前所述,没有内置的
pauseTimeout
function。
However, a simpler way would be to have an if statement within your setTimeout
.但是,更简单的方法是在
setTimeout
中有一个 if 语句。 Something like:就像是:
let timeoutPaused = false;
setTimeout(function(){
if (!timeoutPaused) {
doSomething();
}
}, 1000)
function toggleTimeout() {
timeoutPaused = !timeoutPaused;
}
Then you can just call toggleTimeout
when you want to turn it off or on.然后,您可以在想要关闭或打开它时调用
toggleTimeout
。 Plus you don't even need that as a separate function really, I just put it like so for educational purposes.另外,您甚至不需要将其作为单独的 function 真的,我只是出于教育目的这样说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.