admin 管理员组文章数量: 1086019
I have a carousel of slides that I am rotating through at 5 second intervals. I have a function that clears the timeout to stop the rotation. I am trying to restart the carousel with the code below. The behavior works but incorrectly. Instead of resuming at 5 sec intervals it is quickly flashing through the slides.
t = setTimeout(carousel, 5000);
var interval;
$(document).on('mousemove keyup keypress',function(){
clearTimeout(carousel);
setTimeout(carousel, 6000);
})
I have a carousel of slides that I am rotating through at 5 second intervals. I have a function that clears the timeout to stop the rotation. I am trying to restart the carousel with the code below. The behavior works but incorrectly. Instead of resuming at 5 sec intervals it is quickly flashing through the slides.
t = setTimeout(carousel, 5000);
var interval;
$(document).on('mousemove keyup keypress',function(){
clearTimeout(carousel);
setTimeout(carousel, 6000);
})
Share
Improve this question
asked Apr 18, 2019 at 18:48
KevMoeKevMoe
4434 silver badges21 bronze badges
1
-
2
You need to use
clearTimeout(t)
.t
is an identifier for the timer. This is what you cancel, not the functioncarousel
. – snwflk Commented Apr 18, 2019 at 18:53
3 Answers
Reset to default 4I think you are clearing timeout on inproper variable. According to the docs it should be id of timeout so:
t = setTimeout(carousel, 5000);
$(document).on('mousemove keyup keypress',function(){
clearTimeout(t);
t = setTimeout(carousel, 6000);
}
Here's the problem:
t = setTimeout(carousel, 5000);
var interval;
$(document).on('mousemove keyup keypress',function(){
clearTimeout(t /* instead of carousel */);
t = setTimeout(carousel, 6000); // also refresh the value of the timeout
})
This
clearTimeout(carousel);
is incorrect. clearTimeout
's argument isn't the callback function, it's the timeout's identifier returned by setTimeout
. Should be something like
t = setTimeout(carousel, 5000);
$(document).on(/* some events */,function(){
clearTimeout(t);
});
$(document).on(/* some other events */,function(){
t = setTimeout(carousel, 6000);
});
本文标签: How do I properly restart a timeout in JavascriptStack Overflow
版权声明:本文标题:How do I properly restart a timeout in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744099347a2533422.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论