2

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!

2 Answers2

1

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

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>
JMP
  • 4,417
  • 17
  • 30
  • 41
  • I found on mdn that document.clear() is no longer supported by most browser. anyway, I'll remember not to use it to prevent any problems. Thanks! – Yuval Megidish Jan 08 '22 at 15:25