skip to Main Content

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


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

    let myTimeout;
    
    function newTime(ob) {
        
        if(ob==undefined){
            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>
    Login or Signup to reply.
  2. 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:

    1) This will give you a variable not defined error

    if (true) {
        let foo = 'ok'; 
    }
    console.log(foo);
    

    2) This won’t:

    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.

    Login or Signup to reply.
    • Avoid the use of inline HTML on* JS handler attributes. Use Element.addEventListener() instead
    • Create an Object (singleton) timer with the desired properties and methods like timer.start(fn) and timer.stop()
    • don’t forget to assign the timeoutId to a variable (timer.tOut) and to clear it when needed.
    • Create a greet function and pass it
    const timer = {
      time: 5000,
      tOut: null,
      stop() {
        clearTimeout(this.tOut);
        console.log("Stop>");
      },
      start(callback) {
        this.stop(); // Stop ongoing timeout (if there's any)
        this.tOut = setTimeout(callback, this.time);
        console.log("Start>");
      }
    };
    
    // Use like:
    const greet = () => {
      document.querySelector("#demo").setHTML("Happy birthday!");
    };
    
    document.querySelector("#timer-start").addEventListener("click", () => {
      document.querySelector("#demo").setHTML("");
      timer.start(greet);
    });
    
    document.querySelector("#timer-stop").addEventListener("click", () => {
      timer.stop();
    });
    <button type="button" id="timer-start">Start New</button>
    <button type="button" id="timer-stop">Stop!</button>
    <h2 id="demo"></h2>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search