Sunday, May 24, 2026
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

4 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS