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>
3
Answers
You will want to move the declaration outside of your newTime function as the scope was limited to just that first call of newTime. Also use let and not const.
That’s because
const
andlet
variables are block-scoped. In your case, you declaredmyTimeout
inside the if block, so themyTimeout
variable will only be available inside that if block.To illustrate this better:
1) This will give you a variable not defined error
2) This won’t:
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.
on*
JS handler attributes. UseElement.addEventListener()
insteadtimer
with the desired properties and methods liketimer.start(fn)
andtimer.stop()
timer.tOut
) and to clear it when needed.greet
function and pass it