skip to Main Content

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);
}

2

Answers


  1. Try this:

    function startTimer () {
      let count = 20;
      const timer = setInterval(function() {
        count--;
        console.log(count);
        document.getElementById("timer").innerContent = count.toString();
        if (count === 0) {
          clearInterval(timer);
          console.log("Time's up!");
        }
      }, 1000);
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search