Search code examples
javascriptsettimeoutsetintervalclearintervalcleartimeout

Is there any technical point in clearing or reassigning variables assigned to a setTimeout return value once the timeout executes?


Sometimes in setTimeout functions you want to make sure it doesn't already exist before executing an action.

Upon execution of a setTimeout, is there any value in clearing/re-assigning the variable containing the timeout ID? What about setInterval?

You'll notice in my example timer1 executes 2 logs, whereas timer2 does not.

function renderUtility(name, value) {
  var el = document.createElement('p');
  el.textContent = name + ": " + value
  document.body.appendChild(el);
}

var timer1 = setTimeout(function() {
  clearTimeout(timer1);
  renderUtility('timer1', timer1);
  if (timer1) renderUtility('timer1', "I exist");
}, 1000);

var timer2 = setTimeout(function() {
  clearTimeout(timer2);
  timer2 = null;
  renderUtility('timer2', timer2);
  if (timer2) renderUtility('timer2', "I exist");
}, 1000);


Solution

  • When clearing a setTimeout/ setInterval, should the variable containing this function also be set to null?

    No. There's just no reason to do that. The variable contains an integer id for the timer/interval, not a function; it doesn't hold onto anything.

    And of course, there's no more reason to call clearTimeout from the timeout callback itself, as the timeout has already expired by then.

    You'll notice in my example timer1 executes 2 logs, whereas timer2 does not.

    Just remove the if test for the id and both will work the same. When you're clearing timer/interval, you usually know what you've done.

    If, and only if, you use the variable that contains the id for something else, like storing some state (is a timer active?), then it can make sense to set it to some different value when it has run or been cleared.