clearTimeout() not working

In this small app when you click “Next”, and the joke is a one-liner, a stick man pops up most of the time after 2 seconds, the event listener is on line 59. On line 83 I have memeTimeout that I clear at the top of the event listener so that if the user clicks “Next” before the stick man is displayed, the timeout is cleared and restarted again if the next joke is also a one liner. What’s happening now though, is that if I cycle through the jokes quickly, all those uncleared timeouts make the stick men appear rapidly one after another. How can I clear the timeout? Here’s the project https://codepen.io/Montinyek/pen/KKxLorE?editors=1111

P.S choose English as that’s the language with the most one-liners

  1. I wouldn’t save setTimeout to a variable (memeTimeout). Keep the name as is, otherwise, it is just unnecessarily confusing.

  2. When calling setTimeout it returns the id you need to use with clearTimeout. Save that id in a top-level variable and pass it to clearTimeout

The relevant part of the code if it wasn’t clear.

clearTimeout(id);

// let memeTimeout = setTimeout;
let id;

id = setTimeout(() => {
  displayMemes();
}, 2000);

So do I have to put clearTimeout(id) in the global scope?

I’m still confused as to what to put where. I went through the MDN documentation but didn’t find a solution.

You can create the call to setTimeout and assign it to a variable anywhere you want but to clear it later. The catch is where ever you write clearTimeout(yourTimeOutIdVariable), it must be able to access the variable. This means either putting it in the same scope.

The following will not work because the id variable is not within the scope of the clearTimeout.

function createTimeout() {
  let id = setTimeout(function() {
    console.log('do something')
  }, 2000);
}

createTimeout();
clearTimeout(id);  // id is only accessible from within the `createTimeout` function.

This will work:

let id = setTimeout(function() {
    console.log('do something')
  }, 2000);
clearTimeout(id); // works because `id` is defined in the same scope (global scope) as the call to `clearTimeout` function.

This will also work:

function stopTimeout() {
  clearTimeout(id);
}
let id = setTimeout(function() {
    console.log('do something')
  }, 2000);
stopTimeout(); // works because `id` is defined at a higher scope level (global scope) than the call to this function.

Thank you, it works now

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.