如何停止正在运行的自定义jQuery函数?

时间:2016-09-15 16:14:00

标签: javascript jquery

我有一个自定义的jQuery函数。当它每5秒运行一次。

(function($) {
        $.fn.mycustomfunction = function() {
            interval = setInterval(function() {
                console.log("I am running every 5 seconds");
            }, 5000);
        }
        return this;
    };
})(jQuery);

$("#container").mycustomfunction();

我有一个

clearInterval(interval);

停止,但我也想彻底停止这个功能。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您添加到this对象的函数将附加到您的对象上,简单且天真的解决方案将遵循:

(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();