Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Last active July 29, 2024 10:54
Show Gist options
  • Save irazasyed/305594865c4b4d0b6716 to your computer and use it in GitHub Desktop.
Save irazasyed/305594865c4b4d0b6716 to your computer and use it in GitHub Desktop.
JavaScript: setTimeout Memory Leak Prevention.
// 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);
}
@DIY0R
Copy link

DIY0R commented Jul 29, 2024

  1. If your code has the ability to call setTimeout frequently, it is useful to clear previous timers.
function delayedAlert() {
  if (timeoutID) {
    window.clearTimeout(timeoutID);
  }
  timeoutID = window.setTimeout(slowAlert, 2000);
}
  1. Calling clearTimeout inside the slowAlert function is redundant because the timer has already completed its work, and clearTimeout cannot cancel the function execution after it has been called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment