This content originally appeared on DEV Community and was authored by Javien Lee
ms
ms converts various time formats to milliseconds and vice versa.
/* time format to milliseconds */
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
/* milliseconds to time format */
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
Why do we need this?
It's okay to use milliseconds directly in your code.
setTimeout(() => {
console.log('Hi')
}, 180_000)
But this might not be a good practice, because it's hard to tell how many minutes 180,000 milliseconds is at a glance.
You can improve readability by commenting or using constants.
const THREE_MINUTES_IN_MS = 180_000
setTimeout(() => {
console.log('Hi')
}, THREE_MINUTES_IN_MS)
I actually used to write in this way, and if you're not handling milliseconds a lot, this is a better option than ms
.
However, if you're not, ms
is a good choice. You don't have to write an extra variable, and it's much easier to change the time. 😋
This content originally appeared on DEV Community and was authored by Javien Lee

Javien Lee | Sciencx (2024-08-31T09:11:29+00:00) [Daily Package] ms. Retrieved from https://www.scien.cx/2024/08/31/daily-package-ms/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.