user3304007 user3304007 - 1 year ago 73
Javascript Question

Dynamically added function still running even after remove from DOM

This script has been added dynamically. It has a timeout function, means that it runs every 5 seconds.



(function( $ ){

$.fn.baslatmesajlari = function() {


console.log("I am running");

}, 5000);

return this;
})( jQuery );



I load this function to a div using;


And when I do


The script is still running. How can I stop it run ?

Answer Source

You must have a reference to the interval id, then, when you want to stop it's execution, call clearInterval(the_id)

let interval = null //this is the variable which will hold the setInterval id
$(document).ready(function () {
  (function ($) {
    $.fn.baslatmesajlari = function() {
      interval = setInterval(function () { 
        console.log('I am running')
      }, 5000)
      return this

And then:

clearInterval(interval) // it should stop the function.

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download