Thursday, November 20, 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

1 COMMENT

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6778 POSTS0 COMMENTS
Nicole Veronica
11927 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6905 POSTS0 COMMENTS
Ted Musemwa
7162 POSTS0 COMMENTS
Thapelo Manthata
6861 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS