Last active
July 29, 2024 10:54
-
-
Save irazasyed/305594865c4b4d0b6716 to your computer and use it in GitHub Desktop.
JavaScript: setTimeout Memory Leak Prevention.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout | |
var timeoutID; | |
delayedAlert(); | |
function delayedAlert() { | |
timeoutID = window.setTimeout(slowAlert, 2000); | |
} | |
function slowAlert() { | |
alert("That was really slow!"); | |
clearAlert(); | |
} | |
function clearAlert() { | |
window.clearTimeout(timeoutID); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
clearTimeout
inside theslowAlert
function is redundant because the timer has already completed its work, andclearTimeout
cannot cancel the function execution after it has been called.