Creating a 20 second timer doesn't work and I'm trying to understand why

92 Views Asked by At

I've been trying to implement the following code into my website:

let count = 20;
const timer = setInterval(function() {
  count--;
  console.log(count);
  if (count === 0) {
    clearInterval(timer);
    console.log("Time's up!");
  }
}, 1000);

<p>Your time is running out... <span id="timer"></span> sec</p>

I got this span I want to insert the countdown into and I've been trying many options of which none worked. I'm quite new to JavaScript so appreciate a hint on what I am doing wrong.

Amongst other things I tried the following but nothing really happened..

function startTimer () {
  let count = 20;
const timer = setInterval(function() {
  count--;
  console.log(count);
  if (count === 0) {
    clearInterval(timer);
    console.log("Time's up!");
  }
}, 1000);
  let countdown = document.getElementById("timer").innerContent;
  count = countdown;
  console.log(countdown);
}
1

There are 1 best solutions below

3
duckstery On

I have some suggestion

Don't reassign count

The code below will change your count to something weird and it will break your timer

count = countdown;

count is a number from 20 to 0. You use it to countdown, so let it be

Call your method

I don't know if you've called startTimer or not. But make sure you call it

Change the way to assign innerContent

First, you should use innerText instead

Second, you should change your code from

let countdown = document.getElementById("timer").innerContent;
count = countdown;

To this

let countdown = document.getElementById("timer");
countdown = count;

This will fix your first problem and set 20 to any tag with id="timer" . Only assign document.getElementById("timer") to countdown (not document.getElementById("timer").innerText) because it's an object. So it can be pass by reference

Display timer

Now, you can display countdown value on screen with few adjustment

function startTimer() {
  let count = 20;
  let countdown = document.getElementById("timer");
  const timer = setInterval(function () {
    count--;
    console.log(count);
    countdown.innerText = count;
    if (count === 0) {
      clearInterval(timer);
      console.log("Time's up!");
    }
  }, 1000);
}

startTimer();

Everytime count change, replace countdown.innerText with count's value

Hope this help