-4

I have a custom jQuery function. When it runs every 5 seconds.

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

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

I have a

clearInterval(interval);

to stop, but I also want to stop the function completely. How can I do that ?

kosmos
  • 4,253
  • 1
  • 18
  • 36
user3304007
  • 446
  • 1
  • 7
  • 17
  • 1
    That's exactly what `clearInterval` does. It stops that function from executing at that interval. What behavior are you seeing that you want to correct? What's the actual problem? (Note also that the code shown has syntax errors, so the behavior is undefined if it even executes at all.) – David Sep 15 '16 at 16:17
  • 1
    You can re-declare a function at any point `$.fn.mycustomfunction = function(){ return; }`.. But in your code, only the code inside your function will be executed again. Your interval is a global variable so clearing it your function won't execute anymore. This is, your function is currently fully stopped – kosmos Sep 15 '16 at 16:19
  • You have syntax error, when you want the function stop – Abdelrahman M. Allam Sep 15 '16 at 16:23
  • @AbdelrhmanMohamed I just ask how to stop completely, when I want to stop is up to me. – user3304007 Sep 15 '16 at 16:24
  • @AbdelrhmanMohamed Where's the syntax error exactly? – kosmos Sep 15 '16 at 16:26
  • 1
    the `}` before `return this;` – Abdelrahman M. Allam Sep 15 '16 at 16:28
  • Oh finally I see it. Good eye – kosmos Sep 15 '16 at 16:31
  • @user3304007 What do you mean when you say you want the function to "stop"? `clearInterval()` will stop it running every 5 seconds. Perhaps you should post the content of your function to clarify what exactly the problem is. – BadHorsie Sep 15 '16 at 16:33

1 Answers1

2

Functions you add to this object will be attached to your object and Simple and naive solution will follow:

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

to stop use

var feature = $("#container").mycustomfunction();
feature.stop();