Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
can't use clearInterval

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!