[英]Stopping a running function in javascript/jquery on click event
我在jquery中有一个幻灯片功能,想要在特定的click事件上停止。 幻灯片功能在这里:
function slider(){
setInterval(function(){
var cur = $('img.active');
cur.fadeOut('fast');
cur.removeClass('active');
cur.css('opacity','0');
cur.addClass("hidden");
var nextimg;
if (!cur.hasClass("last")){
nextimg = cur.next("img");
}
else {
nextimg = cur.prev().prev().prev();
}
nextimg.removeClass("hidden").fadeIn('slow').css('opacity','1').addClass('active');
},5000);
}
我一直在阅读有关.queue的信息,但不确定如何正确使用它,我可以从队列中调用函数,然后在单击事件中清除队列吗? 我似乎无法弄清楚使它可行的语法。 关于此或另一种在单击时停止运行功能的方法的建议,将不胜感激。
对于它的价值,通常建议使用递归setTimeout而不是setInterval。 我进行了更改,并对语法进行了一些调整。 但这是我认为想要的基本实现。
// Store a reference that will point to your timeout
var timer;
function slider(){
timer = setTimeout(function(){
var cur = $('img.active')
.fadeOut('fast')
.removeClass('active')
.css('opacity','0')
.addClass('hidden'),
nextimg = !cur.hasClass('last') ? cur.next('img') : cur.prev().prev().prev();
nextimg.removeClass('hidden')
.fadeIn('slow')
.css('opacity','1')
.addClass('active');
// Call the slider function again
slider();
},5000);
}
$('#someElement').click(function(){
// Clear the timeout
clearTimeout(timer);
});
将setInterval的结果存储在变量中。
然后使用clearInterval将其停止。
存储setInterval
返回的值,使用intervalId
清除它,单击处理程序应如下所示:
function stopSlider() {
//prevent changing image each 5s
clearInterval(intervalId);
//stop fading the current image
$('img.active').stop(true, true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.