Created
April 15, 2024 09:56
-
-
Save ravisiyer/8aa51d55956f7e2a66b910daf0c85892 to your computer and use it in GitHub Desktop.
JavaScript: setTimeout does NOT require a clearTimeout unless you want to cancel it before it fires (once)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Ref: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#examples --> | |
<button onclick="delayedMessage();">Show a message after two seconds</button> | |
<button onclick="clearMessage();">Cancel message before it happens</button> | |
<div id="output"></div> | |
<script> | |
let timeoutID; | |
function setOutput(outputContent) { | |
console.log("setOutput() called"); | |
document.querySelector("#output").textContent += outputContent; | |
} | |
function delayedMessage() { | |
timeoutID = setTimeout(setOutput, 2 * 1000, "That was really slow!"); | |
} | |
function clearMessage() { | |
clearTimeout(timeoutID); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment