Javascript 如何停止正在运行的自定义jQuery函数?
我有一个自定义jQuery函数。当它每5秒运行一次时Javascript 如何停止正在运行的自定义jQuery函数?,javascript,jquery,Javascript,Jquery,我有一个自定义jQuery函数。当它每5秒运行一次时 (function($) { $.fn.mycustomfunction = function() { interval = setInterval(function() { console.log("I am running every 5 seconds"); }, 5000); } return this;
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 5000);
}
return this;
};
})(jQuery);
$("#container").mycustomfunction();
我有一个
clearInterval(interval);
停止,但我也想完全停止该函数。我如何才能做到这一点?您添加到
此对象的函数将附加到您的对象,简单而朴素的解决方案如下所示:
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 1000);
this.stop= function(){
clearInterval(interval);
}
// another function
this.alert = function(msg){
alert(msg)
}
return this;
};
})(jQuery);
停止使用
var feature = $("#container").mycustomfunction();
feature.stop();
这正是clearInterval
所做的。它会停止该函数在该时间间隔执行。你看到什么样的行为需要纠正?实际的问题是什么?(还请注意,显示的代码有语法错误,因此即使它执行了,行为也未定义。)您可以在任意点重新声明函数$.fn.mycustomfunction=function(){return;}
。。但是在代码中,只有函数中的代码会再次执行。您的间隔是一个全局变量,因此清除它后,您的函数将不再执行。也就是说,您的函数当前已完全停止。您需要函数时出现语法错误stop@AbdelrhmanMohamed我只是问如何完全停止,何时停止取决于我自己代码>