JavaScript(JS) JS create countdown timer
You can create a countdown timer in JavaScript using the setInterval()
method to run a function at regular intervals and update the display of the remaining time. Here's an example:
function countdown(minutes) { let seconds = minutes * 60; const timer = setInterval(function() { const minutesLeft = Math.floor(seconds / 60); let secondsLeft = seconds % 60; secondsLeft = secondsLeft < 10 ? '0' + secondsLeft : secondsLeft; console.log(minutesLeft + ':' + secondsLeft); if (--seconds < 0) { clearInterval(timer); console.log('Countdown finished'); } }, 1000); } countdown(5);Source:wi.wwgiftidea.com
In the above example, we define a function countdown()
that takes the number of minutes to count down as an argument. We initialize a variable seconds
to the number of seconds in the given number of minutes. We then use the setInterval()
method to run a function every second, which updates the display of the remaining time by calculating the number of minutes and seconds left and logging them to the console. We also check if the countdown has finished by decrementing the seconds
variable and clearing the interval when it reaches 0. Finally, we call the countdown()
function with a value of 5 to start the countdown timer.
When the code is executed, the countdown timer will start and display the remaining time in minutes and seconds every second. When the countdown reaches 0, the message 'Countdown finished'
will be printed to the console. Note that this implementation only logs the remaining time to the console and does not update the display of a webpage or perform any other actions.