【问题标题】:How can I stop custom jQuery function which is running?如何停止正在运行的自定义 jQuery 函数?
【发布时间】:2016-09-15 16:14:00
【问题描述】:

我有一个自定义的 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);

停止,但我也想完全停止该功能。我该怎么做?

【问题讨论】:

  • 这正是clearInterval 所做的。它会阻止该函数在该时间间隔执行。你看到什么行为是你想要纠正的?实际问题是什么? (另请注意,显示的代码有语法错误,因此即使它执行,行为也是未定义的。)
  • 你可以在任何时候重新声明一个函数$.fn.mycustomfunction = function(){ return; }.. 但是在你的代码中,只有你函数内部的代码会被再次执行。您的时间间隔是一个全局变量,因此清除它您的函数将不再执行。也就是说,您的功能目前已完全停止
  • 你有语法错误,当你想要函数停止时
  • @AbdelrhmanMohamed 我只是问如何完全停止,何时停止取决于我。
  • } 之前的return this;

标签: javascript jquery


【解决方案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();

【讨论】:

    猜你喜欢
    • 2011-11-19
    • 1970-01-01
    • 2014-03-23
    • 2018-12-25
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    相关资源
    最近更新 更多