"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > [Daily Package] ms

[Daily Package] ms

Published on 2024-11-03
Browse:780

[Daily Package] ms

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. ?

Release Statement This article is reproduced at: https://dev.to/javien/daily-package-ms-545b?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3