views:

260

answers:

3

Let's say I do this:

$("#content").load(...);

Within what I'm loading some javascript is included:

var myCounter = 0;
var myInterval = setInterval(function(){
   myCounter++;

   $("#counter-display").html("Count: "+myCounter);
});

For an unknown reason, if I reload the content with $("#content").load(...); - myInterval is now being called twice.

I tried doing something like:

if (myInterval !== undefined){
   //dont set interval again
}

However, it doesn't work. Does anyone know any method so that myInterval is cleared on .load, without needing to put the javascript outside of the loaded file?

A: 

Your code is executing twice.

Try checking if (typeof myInterval !== "undefined") before declaring the variable.

SLaks
Tested - not working. It seems each "myInterval" is actually treated separately in the DOM.
Joe
Is your code in a function?
SLaks
Yes. Either way, Nick Craver's solution works fine.
Joe
+2  A: 

Try keeping the interval and count in the data object on the counter element, like this:

var disp = $("#counter-display");
if(!disp.data("interval")) {
  disp.data("interval", setInterval(function() {
    var count = (disp.data("count") || 0) + 1;
    disp.data("count", count).html("Count: " + count);
  }, 500));
}

A bit more code once, but much cleaner for global variables, etc.

Nick Craver
I thought of doing this initially, but I wanted to try a method without needing to fetch the value from the html each time. However, this does work best so I will be using this. Thanks!
Joe
After further testing, although this method words to update the count displayed, when trying to use that count within the script it still doubles up. I couldn't find any solution, other than to put my script OUTSIDE of the loaded content (eg. on the page where I do the .load()).
Joe
@Joe: You're probably re-creating the `@counter-display` element. Put the data in an element that doesn't get replaced.
SLaks
A: 

You'll probably find that myInterval is being defined in some local scope.

Try using:

var myCounter = 0;
myInterval = setInterval(function(){
   myCounter++;

   $("#counter-display").html("Count: "+myCounter);
});

myInterval will now be declared in the global scope.

You can of course use clearInterval, and do clearInterval(myInterval) which will also ensure only on instance of the interval is in use.

Matt
If you .load this code twice, it's not counted as global so this wouldn't work. clearInterval would only clear the myInterval that was loaded, but not the second loaded myInterval. confusing..
Joe
A variable is declared as global unless the var statement is used. `myInterval = ....` makes myInterval global; almost equivalent to `window.myInterval = ...`
Matt