Reputation: 8277
I have a setTimeOut which i have assigned to a div like this:
function update(div,data){
div._myTimer = setTimeout(function() { update(data);},1);
}
But for some reason when i remove the div from the page the time out still runs.
For example lets say i clear the parent of div
by doing:
parent.innerHTML = '';
Shouldn't this cancel my time out because the div no longer appears in the DOM? Or have i misunderstood something.
Upvotes: 3
Views: 102
Reputation: 225
The timeout once set does not need the div to exist. You should remember the reference for the timeout and clear it manually before you clear the div.
When you remove the div by setting the innerHTML of the parent, you can look for every div that is going to be removed and check if it has the _myTimer property set and in the case you clear the timer.
for (var i=0, ilen=parent.childNodes.length; i<ilen; i++) {
if (parent.childNodes[i]._myTimer) {
clearTimeout(parent.childNodes[i]._myTimer);
}
}
Or if you delete the div this way, you can acces the reference directly:
clearTimeout(div._myTimer);
div.parentNode.removeChild(div);
Not with innerHTML = '', this way you have more control over the elements that will be removed
Upvotes: 1
Reputation: 700552
What's returned from the setTimout
method isn't something that is needed from the timer to run, it's just a handle that can be used to stop the timer.
Losing that handle only means that you can't use the clearTimeout
method to stop the timer.
Upvotes: 1
Reputation: 172518
You need the clearTimeout
to do it. You can try something like this:-
function update(div,data){
div._myTimer = setTimeout(function() { update(data);},1);
}
function remove_div(event) {
// do stuff
clearTimeout(timerId);
}
Upvotes: 0
Reputation: 24362
You've misunderstood. Removing the div from the document doesn't clear the timeout. You'll have to use clearTimeout
to cancel it.
Upvotes: 0