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
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.