How to Returns the milliseconds (from 0-999) in JavaScript ?


There are multiple ways to return the milliseconds (from 0-999) in JavaScript:

Method 1: Using the getMilliseconds() method of the Date object

const date = new Date();
const milliseconds = date.getMilliseconds();
console.log(milliseconds); // Output: 123 (or any other value between 0-999)

Method 2: Using the % operator to get the remainder after dividing the timestamp by 1000

const timestamp = Date.now();
const milliseconds = timestamp % 1000;
console.log(milliseconds); // Output: 123 (or any other value between 0-999)

Method 3: Using the performance.now() method of the Performance object (available in modern browsers)

const performance = window.performance || {};
const milliseconds = performance.now() % 1000;
console.log(milliseconds); // Output: 123 (or any other value between 0-999)

Note: All of these methods return the milliseconds at the time of execution, so the value may be different each time the code is run.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.