Reputation: 7337
I'm using jQuery to "blink" some text when loading (after an AJAX call), but whenever I call clearInterval, I get an "undefined" error.
Here's a snippet of my code:
OrderId="a12345";
var AllIDs = {};
AllIDs[OrderId] = setInterval(
function() {j$("#" + OrderId + "_MessageListSize").fadeIn(200).fadeOut(200)},
200
);
Then later, after the AJAX call completes:
OrderId="a12345"; var myid = AllIDs[OrderId]; clearInterval(myid);
Why won't clearInterval stop the animation? Does it have to do with how I'm using associative arrays object literals?
Thanks in advance!
Upvotes: 0
Views: 504
Reputation: 1889
JavaScript doesn't have associative arrays, those are object literals. HTML IDs can't start with a number. Your problem is you are scheduling events too quickly and they're getting backed up. Every 200ms, you have it set to schedule two tasks that each take 200ms to complete (400ms).
You could tweak your intervals but it is really a better idea to use setTimeout() and schedule the next timeout in the animation callback if the AJAX hasn't completed yet otherwise do nothing and it will halt. No need to clearInterval.
Something like this...
function scheduleBlink() {
AllIDs[OrderId] = setTimeout(
function() {
j$("#" + OrderId + "_MessageListSize").fadeIn(200).fadeOut(200, function () {
if (!ajaxDone) {
scheduleBlink();
}
else {
return;
}
}))
},
200
);
}
scheduleBlink()
Upvotes: 3
Reputation: 1047
I suspect the problem is that you are using a timeout interval of 200 ms. The fade out takes 200 ms and the fade in then takes another 200 ms, however, that function is called every 200 ms, so in the time the first call completes, another call has already started. Try clearing the interval very quickly after you start it and see if it stops after a couple of seconds.
Here's an example html file that works correctly for me, stopping the flashing after 2 seconds.
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
</head><body>
<h1 id="target">Hello, World</h1>
<script type="text/javascript">
timeout_id = setInterval(function(){
$("#target").fadeOut(200).fadeIn(200);
}, 400);
setInterval(function(){ clearInterval(timeout_id); }, 2000);
</script>
</body>
</html>
As an example, if I change the 400 ms above to say, 100 ms, and refresh the page, it takes much longer for the flashing to stop.
Upvotes: 1