Home > front end >  can't use clearInterval
can't use clearInterval

Time:01-08

in trying to create a page that will show the current time which will refresh every x seconds - x is a user input i use setInterval and clearInterval but it looks like the clearInterval doesn't have any effect at all :( here's the code:

 <script>
      let changeTime = () => {
        let secs = document.getElementById("sec").value * 1000;
        clearInterval(timer);
        let timer = setInterval(() => {
          let d = new Date();
          document.getElementById("example").innerHTML = d.toLocaleString();
          console.log(secs);
        }, secs);
      };

      function clear() {
        clearInterval(timer);
      }

      //both functions are called with an onChange event

thanks!

CodePudding user response:

Your timer variable is local to your changeTime() function. Declare it outside the function.

  let timer;
  let changeTime = () => {
    let secs = document.getElementById("sec").value * 1000;
    clearInterval(timer);
    timer = setInterval(() => {
      let d = new Date();
      document.getElementById("example").innerHTML = d.toLocaleString();
      console.log(secs);
    }, secs);
  };

When the variable is local to the function, it only exists during the time a function call is happening, and a new instance of the variable is created on each call. By declaring it outside the function, the variable and its value persists.

CodePudding user response:

Firstly, let declares a variables as local, and so timer is not visible to clear(). Just remove let (and don't add anything else), and the variable is declared as global.

Second, although clear is not a reserved JavaScript word, it actually calls the obsolete document.clear().

Is "clear" a reserved word in Javascript?

So either change it's name or use window or self to remove the ambiguity.

let changeTime = () => {
    let secs = 100;
    timer = setInterval(() => {
        let d = new Date();
        document.getElementById("out").innerHTML = d.toLocaleString();
        }, secs);
      };

function clear() {
    clearInterval(timer);
    }

changeTime();
 </script>
<span id="out"></span>
<button onclick="self.clear();">clear</button>

  •  Tags:  
  • Related