user3304007 user3304007 - 2 months ago 7
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.

dynamicjs.php

$(document).ready(function(){

(function( $ ){

$.fn.baslatmesajlari = function() {

setInterval(function(){

console.log("I am running");

}, 5000);

return this;
};
})( jQuery );

});

$("body").baslatmesajlari();


I load this function to a div using;

$("#temporarycontent").load("dynamicjs.php");


And when I do

$("#temporarycontent").empty();


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

Answer

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
    }
  })(jQuery)
})
$("body").baslatmesajlari()

And then:

$("#temporarycontent").empty();
clearInterval(interval) // it should stop the function.

Hope it helps.