3 ms·
I got confused here, because in the timers example, I assumed that without calling cancelDemo/clearTimeout, we cannot assume that the timer's function is no lon
by lxe 2y ago
I got confused here, because in the timers example, I assumed that without calling cancelDemo/clearTimeout, we cannot assume that the timer's function is no longer callable. Heck, even WITH clearTimeout... without understanding its implemetation, we cannot assume it's no longer callable by some internal system.
I think you should call cancelDemo() in the article to show that yes, even when we assume that the reference to the closure is cleaned up, the allocation persists.
(() => {
// Assumed implementation of setTimeout
// in which we cannot make assumptions that fn
// is inaccessible after the first invocation
const timers = [];
function mySetTimeout(fn) {
fn();
// retain the function for some reason
// maybe because of timers/intervals implemetation detail
timers.push(fn);
const id = timers.length - 1;
return id
}
function myClearTimeout(id) {
// this makes it to fn has no more references
// but it still gets retained
const fn = timers.splice(id, 1);
// For good measure
delete fn;
}
function demo() {
const bigArrayBuffer = new ArrayBuffer(100_000_000);
const id = mySetTimeout(() => {
console.log(bigArrayBuffer.byteLength);
}, 1000);
return () => myClearTimeout(id);
}
cancelDemo = demo();
// Even when calling clearTimeout,
// bigArrayBuffer is still allocated,
// Which is the crux of the article
cancelDemo();
// Now it's actually deallocated, as
// shows in the article
delete cancelDemo;
})();