Reputation:
I am replacing a div
's content with externally loaded php using the Jquery .load()
function, my problem is that I would like to write my javascript code for php files and save it in the bottom of the file.
So basically when I run the .load()
function, the internal javascript of the file i'm loading, runs too. This works great so far. My problem is that when I run the .load()
function again to load different content with different javascript into my div
, the javascript of the previous file loaded, continues to run.
I need it to stop running the javascript of the last loaded php file, and load the new javascript.
For example, I have 1 div and 5 files, whenever I click a button, using the load()
function, i inject the php and javascript of the page I have selected into the div. If each of my pages has this code at the bottom
setInterval(function(){
console.log("hello");
},1000)
and I load each page 1 at a time, it stores the javascript and in result, runs console logs "hello" 5 times a second.
What I want it to do is remove the previous javascript, and load the new one everytime I select a new page.
How do I achieve this?
Upvotes: 0
Views: 206
Reputation: 207501
You would need to store it into a variable and remove it if it exists.
if (window.myInterval) window.clearInterval(window.myInterval)
window.myInterval = setInterval(function(){
console.log("hello");
}, 1000)
Upvotes: 3
Reputation: 784
Better you call the remove interval by using
clearInterval();
method, because once you call the
setInterval();
method, it will continue doing the function it is said to, until you leave the page or clear the interval.
Upvotes: 1