A digital clock in JavaScript can be created using the setInterval()
function and the Date
object. The setInterval()
function is used to execute a function repeatedly at a specified time interval, and the Date
object is used to get the current date and time.
Here is an example of how to create a basic digital clock in JavaScript:
function displayTime() {
var date = new Date();
var time = date.toLocaleTimeString();
document.getElementById("clock").innerHTML = time;
}
setInterval(displayTime, 1000);
In the above example the function displayTime
is invoked every second (1000ms) using setInterval
function. This function get the current time using the new Date()
object and the toLocaleTimeString()
method, and update the element with the ID “clock” to show the current time.
You also can use template literals to format the time as you prefer
function displayTime() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
document.getElementById("clock").innerHTML = `${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}
setInterval(displayTime, 1000);
This is just a basic example and you can customize it to suit your needs, for example, by styling the clock using CSS, or by adding the date to the clock display.
Also Read:
- Difference Between encodeURIComponent() And encodeURI()
- Convert Comma Separated String Into An Array In JavaScript
- How To Check If A String Is Empty In JavaScript
- How To Sort An Array Of Numbers In JavaScript
- How To Return Multiple Values From A Function In JavaScript
- How To Get The Current URL With JavaScript
- How To Include A JavaScript File In Another JavaScript File
- How To Detect Screen Resolution With JavaScript
- How To parse JSON Into JavaScript
- How To Add Elements To An Array In JavaScript
- How To Generate A Timestamp In JavaScript
- How To Convert A JavaScript Object To JSON String
- How To Add An Element To The Beginning Of An Array
- How To Get The Value From The Input Field In JavaScript
- Adjust The iFrame Height To Fit With Content In JavaScript
- Call Two Functions From The Same onClick Event In JavaScript
- How To Detect When A Window Is Resized Using JavaScript
- How To Reset A Form With JavaScript
- How To Pass JavaScript Variables To PHP
- Difference Between PHP And JavaScript
- Armstrong Number In JavaScript
- How To Determine If A Number Is Odd Or Even In JavaScript
- How To Check If A Number Is A Palindrome In JavaScript
- How To Convert Strings To Uppercase In JavaScript
- How To Convert A String To Lowercase In JavaScript
- Code To Check If Age Is Not Less Than 18 Years In JavaScript
- How To Reverse A Number In JavaScript
- How To Check If A Number Is Prime Using JavaScript
- How To Find Factorial Of A Number In JavaScript
- Sum Of Two Numbers In JavaScript
- How To Display The Current Date And Time In JavaScript