Reputation: 4564
I need to be able to stop a setInterval function while its running. The idea is if the browser is resized then it will the timer (320px or less) here is the interval:
var blurb_scroll = setInterval(function(){
$(".content .blurb-container:first").next().css({'opacity':0}).delay(400).animate({'opacity':1}, 'fast');
$(".content .blurb-container:first").animate({'margin-top':'-190px', 'opacity':'0'}, 'slow', function(){
$(this).appendTo(blurb_container).removeAttr('style');
});
},6000);
Upvotes: 1
Views: 942
Reputation: 53598
Rather than clearing the setInterval interval, start using setTimeout instead:
(function runthis() {
var f = $(".content .blurb-container:first")
f.next()
.css({'opacity':0})
.delay(400)
.animate({'opacity':1}, 'fast')
.animate({'margin-top':'-190px', 'opacity':'0'}, 'slow', function(){
$(this).appendTo(blurb_container).removeAttr('style');
});
if (conditional that says we should keep doing this) {
setTimeout(runthis, 6000);
}
}());
Now you have much finer control over what happens, and if your code has an error, at least it won't keep running your error code forever. If it dies on an error, you never schedule a new timeout.
setInterval. Just not a good idea.
Upvotes: 0
Reputation: 224
You should use clearInterval and jquery .stop() function according to jquery documentation http://api.jquery.com/stop/
Also as jquery states, animations may be stopped globally by setting the property $.fx.off to true. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.
Upvotes: 1
Reputation: 50905
To stop the interval as well as the animations, you need to use clearInterval
(on the interval id) and .stop()
(on the elements).
For example:
clearInterval(blurb_scroll);
$(".content .blurb-container:first").stop();
Upvotes: 1
Reputation: 707
You must use clearInterval. Put the variable with your setInterval as global, then you can stop it anywhere.
<html>
<body>
<input type="text" id="clock">
<script language=javascript>
var int=self.setInterval(function(){clock()},1000);
function clock() {
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("clock").value=t;
}
</script>
</form>
<button onclick="int=window.clearInterval(int)">Stop</button>
</body>
</html>
Here you can find this example e much more info about clearInterval.
Hope it helps!
Upvotes: 1