If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.