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

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

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

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?