[英]Stop setInterval and start it again
I'm using this set interval function: 我正在使用此设置间隔功能:
function ticker(){
setInterval(function(){
$('.slide').fadeToggle();
}, 5000);
}
What I want to do is that when the user clicks on a div
with onclick="topbartoggle"
the setInterval
function stops, and if he clicks again on it the setInterval
function begins to work again: 我想做的是,当用户单击带有
onclick="topbartoggle"
的div
, setInterval
函数停止,并且如果他再次单击它,则setInterval
函数将再次开始工作:
function topbartoggle(){
$('#top-bar').toggleClass('active');
$('.top-bar-box').slideToggle();
$('.top-bar-close').fadeToggle();
}
Any idea on how to do this? 关于如何执行此操作的任何想法?
var tickerID = false;
function ticker(){
tickerID = setInterval(function(){
$('.slide').fadeToggle();
}, 5000);
}
To stop the ticker, use 要停止股票行情,请使用
clearInterval(tickerID);
clearInterval(tickerID);
To start it again, just call ticker(); 要再次启动它,只需调用ticker();即可。
EDIT: Understanding that you need to toggle the ticker, add this to your toggling function: 编辑:了解您需要切换股票行情,将此添加到您的切换功能:
if(tickerID != false) {
clearInterval(tickerID);
tickerID = false;
} else { ticker(); }
setInterval returns a handle you can use to stop the interval, like this: setInterval返回一个可用于停止间隔的句柄,如下所示:
var myInterval = setInterval(function() { // myInterval should be global
something();
}, 5000);
function stopInterval()
{
clearInterval(myInterval);
}
So you can do like this: 所以你可以这样:
<div onclick="stopInterval();anyOtherFunction();"></div> //anyOtherFunction could be any function you want.
Since you want to maintain the same delay, it's probably easiest to just keep the timer running: 由于您希望保持相同的延迟,因此最简单的方法就是保持计时器运行:
var shouldTick = true;
var $slide = $('.slide');
setInterval(function () {
if (shouldTick) {
$slide.fadeToggle();
}
}, 5000);
function topbartoggle() {
shouldTick = !shouldTick;
$('#top-bar').toggleClass('active');
$('.top-bar-box').slideToggle();
$('.top-bar-close').fadeToggle();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.