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
Try this:
I have some suggestion
Don’t reassign
count
The code below will change your
count
to something weird and it will break your timercount
is a number from 20 to 0. You use it to countdown, so let it beCall your method
I don’t know if you’ve called
startTimer
or not. But make sure you call itChange the way to assign
innerContent
First, you should use
innerText
insteadSecond, you should change your code from
To this
This will fix your first problem and set 20 to any tag with
id="timer"
. Only assign
document.getElementById("timer")
tocountdown
(notdocument.getElementById("timer").innerText
) because it’s an object. So it can be pass by referenceDisplay timer
Now, you can display countdown value on screen with few adjustment
Everytime
count
change, replacecountdown.innerText
withcount
‘s valueHope this help