Countdown Timer

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 155:- Countdown Timer

To create a countdown timer in JavaScript, we need to use the setInterval() method. This method repeatedly executes a function after a specified interval. We can use this method to decrement the timer every second until it reaches zero.

Here is an example code for a countdown timer:

htmlCopy code

<!DOCTYPE html> <html> <head> <title>Countdown Timer</title> </head> <body> <div id="timer">10:00</div> <button onclick="startTimer()">Start Timer</button> <script> function startTimer() { let presentTime = document.getElementById('timer').innerHTML; let timeArray = presentTime.split(/[:]+/); let minutes = parseInt(timeArray[0]); let seconds = parseInt(timeArray[1]); let totalSeconds = minutes * 60 + seconds; let timer = setInterval(function() { totalSeconds--; minutes = Math.floor(totalSeconds / 60); seconds = totalSeconds - (minutes * 60); if (seconds < 10) { seconds = "0" + seconds; } document.getElementById('timer').innerHTML = minutes + ":" + seconds; if (totalSeconds == 0) { clearInterval(timer); alert("Time's up!"); } }, 1000); } </script> </body> </html>

In this code, we first create an HTML element with an initial time of 10:00. When the user clicks the "Start Timer" button, the startTimer() function is called.

Inside the startTimer() function, we get the current time from the #timer element and split it into minutes and seconds using the split() method. We then convert these values into integers and calculate the total number of seconds.

We then use the setInterval() method to decrement the totalSeconds value every second. We update the minutes and seconds accordingly and display the new time in the #timer element.

When the totalSeconds value reaches zero, we clear the interval and display an alert to inform the user that the time is up.

17. Objects and Timing Events

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support