I had a question, and wondered if you called setTimeout from an object, then deleted the object, would the setTimeout callback still be called?
Apparently yes.
var container = {
timer: { // the object to be deleted
start: function() {
console.log('start');
setTimeout(this.end, 2000);
},
end: function() {
console.log('end');
},
},
timerStart: function() {
this.timer.start();
setTimeout(this.timerDelete, 1000);
},
timerDelete: function() {
console.log(delete this.timer);
console.log('deleted timer');
},
};
After calling container.timerStart(); I recieve the following:
> container.timerStart();
start
< undefined
true
deleted timer
end
Therefore showing that the object container.timer was successfully deleted, but also that container.timer.end was also called after container.timer was deleted. I understand that delete only removes the reference, and once all references of an object are removed it is removed from memory, but does this mean that setTimeout also stores a reference to its callback?
In essence, my questions are:
- Is
container.timeractually deleted? - Why does the
setTimeoutcallbackcontainer.timer.endstill run? - How does
setTimeoutactually work with reference to this behaviour?
Any feedback or reading resources are greatly appreciated. Thanks!