javascripthtmlfunctioncleartimeout

Javascript Function using a parameter defined in the future


I'm doing a question that appears in 10:10:02 of this video https://youtu.be/EerdGm-ehJQ?t=36602 (Challenge exercise 12f)

The question is as follows:

I figured out the solution but I don't understand how it works. my code is as follows:

let timeoutID;

function updateMessage() {
  const message = document.querySelector('.js-message')

  message.innerHTML = 'Added'

  clearTimeout(timeoutID)

  timeoutID = setTimeout(function() {
    message.innerHTML = ''
  }, 2000)

}
<button onclick="
  updateMessage();
  ">Add to cart</button>


<p class="js-message"></p>

When the clearTimeout(timeoutID) line is ran, it seems to me that the parameter that is being inputted into clearTimeout is defined on the next bit of code below. how is clearTimeout reaching onto the 2 lines of code below and then going back and running itself?

I see that I've put 'let timeoutID' in the first line of the script, but I'm not assigning anything to it. I dont understand this part.


Solution

  • The clearTimeout(timeoutID) works because timeoutID is declared outside the updateMessage function, so it keeps its value across multiple calls of updateMessage. When clearTimeout(timeoutID) runs, it stops the previous timeout (if there was one), then a new setTimeout is started and assigned to timeoutID. This way, each time you press the button, it resets the timer by clearing the old timeout and starting a fresh 2-second countdown.