Moment.js 计时器插件
Moment.js计时器插件 用于创建计时器。它是对JavaScript本地计时器的改进。基本上,它是对setInterval和setTimeout方法的重新编写。它提供了一系列与在moment持续对象上创建和管理计时器相关的函数。
可以使用以下命令进行安装:
npm install moment-timer
以下是此插件中的一些列表函数:
- start
- loop
- duration
- getDuration
- getRemainingDuration
- isStopped
- isStarted
下面的示例将帮助理解计时器插件的一些方法。
示例1:
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.`
);
});
输出:
Timeout Callback executed 1003 ms after script was started.
示例2:
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()}`
);
输出:
Before stop() is called: false
After stop() is called: true
参考: https://momentjs.com/docs/#/plugins/timer/