I'm working on a div (parent) that has two other divs (menu and content) as follow:
<div id="parent">
<div id="menu"></div>
<div id="content"></div>
</div>
The content loaded in content div is an html file that has a few javascript functions, such as an auto-refresh that reloads its content every 5 seconds.
$(document).ready(function () {
setInterval(function () {
grid.reloadDefaultContent(); //this reloads the content on content div.
}, 5000);
}
There are some links on the page that load differents content into the content div. So far so good, until I go back to "home," which has the auto-refresh function. The problem is that the auto-refresh never stopped, and now that I clicked to go to home again, the function is running twice (or how many times I change the page and come back to home), putting session upon.
I'm loading pages using jQuery $.load()
.
Any ideas on how I can make that instance of setInterval runs only once?
Edit: after reading my own question I saw that it was a bit unclear. My main problem is that when I go back to home, my first instance of the setInterval is already running, and a second starts, making the auto-refresh that was 5 seconds go faster, and it'll go faster and faster every time I change the page and go back to home. This is not the behavior I want. What I need is to STOP the instance of setInterval when I change the content on the div, and restart it when I go back to home.
This should do it:
var interval; // make sure that is defined outside of the loaded div content
$(document).ready(function () {
if (typeof interval != "number"){
interval = setInterval(function () {
grid.reloadDefaultContent();
}, 2000);
}
});
It will only initiate one instance of the interval timer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With