JS: window.setInterval still running in the background?
My code is like:
window.setInterval(updateSeconds, 1000);
function updateSeconds() {
var remainingSeconds = $('#seconds').html() - 1;
if(remainingSeconds < 0) {
remainingSeconds = 0;
}
开发者_开发问答 $('#seconds').html(remainingSeconds);
if(remainingSeconds == 0) {
//stop calling updateSeconds
}
}
There is no issue, except that setInterval will still keep calling updateSeconds(), is there a way to stop it?
Yes, you can use clearInterval
to stop a timer:
// Added `var handle`:
var handle = window.setInterval(updateSeconds, 1000);
function updateSeconds() {
var remainingSeconds = $('#seconds').html() - 1;
if(remainingSeconds < 0) {
remainingSeconds = 0;
}
$('#seconds').html(remainingSeconds);
if(remainingSeconds == 0) {
//stop calling updateSeconds
window.clearInterval(handle); // <== added
handle = 0; // <== added
}
}
If your code is at global scope, you probably don't want to create a new global variable called handle
. You can avoid that by wrapping it in a function and then executing the function immediately:
(function() {
var handle = window.setInterval(updateSeconds, 1000);
function updateSeconds() {
var remainingSeconds = $('#seconds').html() - 1;
if(remainingSeconds < 0) {
remainingSeconds = 0;
}
$('#seconds').html(remainingSeconds);
if(remainingSeconds == 0) {
//stop calling updateSeconds
window.clearInterval(handle);
handle = 0;
}
}
})();
Now handle
and updateSeconds
are private to the anonymous function. (Obviously if you need to call updateSeconds
from somewhere else, making it private would be a problem.)
But if they're already inside something (an event handler function, perhaps), you've already got a private scope there and don't need to do that.
精彩评论