OiO.lk Blog HTML Javascript Function using a parameter defined in the future
HTML

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:

  • Click a button in HTML
  • Add a message on the screen
  • Start a ‘setTimeout’ for 2 seconds, at the end of the 2 seconds, remove the message
  • But within that 2 second timeout, press the button again
  • The timeout has to refresh (using clearTimeout) so the timer will continue on for more than the original 2 seconds.

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.



You need to sign in to view this answers

Exit mobile version