Horje
How to Get Milliseconds in JavaScript?

In JavaScript, you can get the current time in milliseconds, which is useful for timestamping events, measuring time intervals, and performing time calculations. JavaScript provides various methods to precisely measure time down to the millisecond, including Date.now(), performance.now(), and the Date object’s getTime() method. These tools enable developers to effectively manage time in their programming tasks.

These are the following methods to get milliseconds in JavaScript:

Using Date Object

In JavaScript, you can easily get the milliseconds by creating a new Date object and using its getMilliseconds() method, which generates the milliseconds part of the current time. This straightforward approach makes accessing time information for developers easier.

Example: To illustrate a new Date object using getMilliseconds() method.

JavaScript
function getCurrentMilliseconds() {
    const now = new Date();
    return now.getMilliseconds();
}

function main() {
    const milliseconds = getCurrentMilliseconds();
    console.log("Milliseconds: " + milliseconds);
}

main();

Output
Milliseconds: 984

Using Performance API

The Performance API gives an accurate way to measure time. Its now() method tells the current time very precisely, useful for checking performance or comparing speeds.

Example: To demonstrate how to use JavaScript’s Performance API to obtain the current time in milliseconds.

JavaScript
function getPerformanceMilliseconds() {
    return performance.now();
}

function main() {
    const milliseconds = getPerformanceMilliseconds();
    console.log("Milliseconds: " + milliseconds);
}

main();

Output
Milliseconds: 48.6021290011704

Using Date.now() method

You can quickly get the current time in milliseconds using the Date class’s now() method. It’s a direct way to get accurate time information whenever you require it.

Example: To illustrate how to utilize JavaScript’s Date.now() method to retrieve the current time in milliseconds.

JavaScript
function getCurrentMilliseconds() {
    return Date.now();
}

function main() {
    const milliseconds = getCurrentMilliseconds();
    console.log("Milliseconds: " + milliseconds);
}

main();

Output
Milliseconds: 1719817895151



Reffered: https://www.geeksforgeeks.org


HTML

Related
How to Add Symbols in HTML? How to Add Symbols in HTML?
How to Upload Files in JavaScript? How to Upload Files in JavaScript?
How to Play Video in Reverse in HTML5 ? How to Play Video in Reverse in HTML5 ?
How to Create Alert Button in HTML? How to Create Alert Button in HTML?
How to Add Icons in HTML? How to Add Icons in HTML?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19