

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set a countdown timer in javascript?
You can create a countdown timer in Javascript using the setInterval method. The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
To create a countdown, we need to check the difference between current time and final time and keep updating the countdown. For example,
Example
let countDownDate = new Date("Jul 21, 2020 00:00:00").getTime(); let x = setInterval(() => { let now = new Date().getTime(); let distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds let days = Math.floor(distance / (1000 * 60 * 60 * 24)); let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); let seconds = Math.floor((distance % (1000 * 60)) / 1000); console.log(days + "d " + hours + "h " + minutes + "m " + seconds + "s"); // If the count down is finished, write some text if (distance < 0) { clearInterval(x); console.log("completed") } }, 1000);
Output
This will give the output −
310d 0h 6m 46s 310d 0h 6m 45s 310d 0h 6m 44s 310d 0h 6m 43s 310d 0h 6m 42s 310d 0h 6m 41s 310d 0h 6m 40s 310d 0h 6m 39s 310d 0h 6m 38s 310d 0h 6m 37s 310d 0h 6m 36s 310d 0h 6m 35s 310d 0h 6m 34s 310d 0h 6m 33s
- Related Questions & Answers
- How to create a countdown timer with JavaScript?
- How to make a countdown timer in Android?
- Making a countdown timer with Python and Tkinter
- How to set a timer in Android using Kotlin?
- C# Program to set the timer to zero
- Binary Countdown Protocol
- How to create a timer using tkinter?
- Timer in C#
- Python Program to Create a Lap Timer
- How to create timer using C++11?
- How to get timer ticks at a given time in Python?
- How to run a timer in background within your iOS app
- How can we implement a timer thread in Java?
- Timer objects in Python
- Timer Class in Java
Advertisements