Friday, September 19, 2025
HomeLanguagesJavascriptMoment.js Timer Plugin

Moment.js Timer Plugin

The Moment.js Timer Plugin is used for the creation of timers. It is an improvement over JavaScript’s native timer. Essentially, it is a rewriting of the setInterval and setTimeout methods. It provides a list of functions concerned with creating and managing timers on top of moment duration objects.

It can be installed using the following command:

npm install moment-timer

 

The following are some of the lists functions in this plugin:

  • start
  • loop
  • duration
  • getDuration
  • getRemainingDuration
  • isStopped
  • isStarted

The below examples will help to understand some of the methods of the Timer Plugin.

Example 1:

Javascript




import moment from 'moment';
import timer from "moment-timer";
  
let start = new Date().getTime();
let t = new moment
    .duration(1000)
    .timer({ start: true }, function () {
    console.log(
        `Timeout Callback executed 
         ${(new Date().getTime() - start)}
         ms after script was started.`
    );
});


Output:

Timeout Callback executed 1003 ms after script was started.

Example 2:

Javascript




import moment from 'moment';
import timer from "moment-timer";
  
let t = new moment
    .duration(10000)
    .timer(function () {
    console.log('Finished Timer');
});
  
t.start();
console.log(
    `Before stop() is called: ${t.isStopped()}`
);
  
t.stop();
console.log(
    `After stop() is called: ${t.isStopped()}`
);


Output:

Before stop() is called: false
After stop() is called: true

Reference: https://momentjs.com/docs/#/plugins/timer/

RELATED ARTICLES

Most Popular

Dominic
32301 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6666 POSTS0 COMMENTS
Nicole Veronica
11840 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11898 POSTS0 COMMENTS
Shaida Kate Naidoo
6781 POSTS0 COMMENTS
Ted Musemwa
7056 POSTS0 COMMENTS
Thapelo Manthata
6739 POSTS0 COMMENTS
Umr Jansen
6745 POSTS0 COMMENTS