Saturday, February 7, 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

2 COMMENTS

Most Popular

Dominic
32493 POSTS0 COMMENTS
Milvus
126 POSTS0 COMMENTS
Nango Kala
6864 POSTS0 COMMENTS
Nicole Veronica
11990 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12083 POSTS0 COMMENTS
Shaida Kate Naidoo
7000 POSTS0 COMMENTS
Ted Musemwa
7241 POSTS0 COMMENTS
Thapelo Manthata
6951 POSTS0 COMMENTS
Umr Jansen
6936 POSTS0 COMMENTS