Reputation: 6431
I use setInterval as below and until now i have used it exactly same way but if element is removed from Document this interval will continue to work unnecessarily. I haven't seen an example that handle this case yet.
Is it unnecessary to handle this case ? And if i have to handle it so what would be best way break interval ?
var element = $('bla');
setInterval(function () {
element.text(new Date().toString());
}, 1000);
Upvotes: 2
Views: 355
Reputation: 147413
Just a comment:
@hicurin, you might consider using an immediately invoked function expression (IIFE) instead:
(function() {
var element = $('bla');
var interval = setInterval(function () {
element.text(new Date());
// check if element is removed
if(!$('bla').length && interval) {
clearInterval(interval);
}
}, 1000);
}());
Upvotes: 3
Reputation: 3965
Try this:
var element = $('bla');
var int = setInterval(function () {
element.text(new Date().toString());
// check if element is removed
if(!(element.length > 0) || element == undefined){
clearInterval(int);
}
}, 1000);
Upvotes: 1