Search code examples
javascripttimer

JS - clearTimeout vs. delete


I am using a timer to call a function after 1 minute.

var timer = setTimeout(function() {
    console.log("timer trigger");
}, 10000);

clearTimeout(timer); clears the timer and delete timer; returns false.

Why delete is not working with timers?


Solution

  • delete timer; won't actually do anything, because you can only delete object properties. timer is not an object property, so it can't be deleted. (Technically it's a property of the window object, but Javascript specifies that unless you assign window.timer then you can't delete top level variables). When delete returns false that means there was nothing to delete.

    The timeout you've set is a function reference. That's what needs to be removed, not the integer returned by setTimeout. Only the runtime environment (browser) knows how to remove that function reference by its id, which is what's returned from setTimeout.