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

321
Views
Svelte: clearInterval does not cancel setInterval

Problem

I have a simple timer which should be paused or reset by clicking a button. My problem is that the interval keeps running. Basically I save the identifier in the time variable and try to reset it when a pause or stop button is clicked. The variable should be publicly accessible, so I don't know where it goes wrong.

Code

Here is the (shortened) code in question:

  let total = 0;
  let minutes = 0;
  let seconds = 0;
  let hours = 0;
  let running = false;
  let time;

  $: normalizedHours = hours > 9 ? hours : `0${hours}`;
  $: normalizedMinutes = minutes > 9 ? minutes : `0${minutes}`;
  $: normalizedSeconds = seconds > 9 ? seconds : `0${seconds}`;
  $: title = `${normalizedHours}:${normalizedMinutes}:${normalizedSeconds}`;

  function run() {
    if (running) {
      return;
    }
    running = true;

    timer();
  }

  function timer() {
    time = setInterval(() => {
      total++;

      if (seconds == 59) {
        seconds = 0;

        if (minutes == 9) {
          minutes++;
        } else if (minutes == 59) {
          minutes = 0;

          if (hours == 23) {
            hours = 0;
          }
          hours++;
        } else {
          minutes++;
        }
      } else {
        seconds++;
      }
    }, 1000);
  }

  function pause() {
    clearInterval(time);
    time = null;    
    running = false;
  }

  function reset() {
    pause();
    hours = 0;
    minutes = 0;
    seconds = 0;
  }

  const buttons = [
    { title: "Play", click: run, icon: "play" },
    { title: "Pause", click: pause, icon: "pause" },
    { title: "Reset", click: reset, icon: "stop" },
  ];
</script>

<section>
  <form on:submit|preventDefault={run}>
    <div class="controls">
      {#each buttons as { title, click, icon }}
        <button {title} on:click={click}>
          <i class={`fa fa-${icon}-circle`} />
        </button>
      {/each}
    </div>
    <div class="time">{normalizedHours}</div>
    <span>:</span>
    <div class="time">{normalizedMinutes}</div>
    <span>:</span>
    <div class="time">{normalizedSeconds}</div>
  </form>
</section>

Repl

Here is a link to the repl where you can see / debug the problem.

about 4 years ago · Juan Pablo Isaza
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!