I use setTimeout to create a time countdown of 5 seconds (it works), but I want to stop the setTimeout with Button Stop, but I have an error finding the variable.
What is the error?
function newTime(ob) {
if(ob==undefined){
const myTimeout = setTimeout(myGreeting, 5000);
console.log("Start>");
}
if(ob=="stop"){
if(myTimeout==true){
clearTimeout(myTimeout);
console.log("Stop>");
}
}
}
function myGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
function myStopFunction() {
newTime("stop");
}
<h1>The Window Object</h1>
<h2>The setTimeout() and clearTimeout() Methods</h2>
<p>Click "Stop" to prevent myGreeting() to execute. (You have 5 seconds)</p>
<button onclick="myStopFunction()">Stop!</button>
<button onclick="newTime()">new Time Start</button>
<h2 id="demo"></h2>
That's because const
and let
variables are block-scoped. In your case, you declared myTimeout
inside the if block, so the myTimeout
variable will only be available inside that if block.
To illustrate this better:
if (true) {
let foo = 'ok';
}
console.log(foo);
let foo;
if (true) {
foo = 'ok';
}
console.log(foo);
Also, you'll have to declare your variable outside your function, otherwise you won't have access to the value assigned to it on the previous call.