Moment.js Timer Plugin
Last Updated :
07 Jul, 2022
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/
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...