I created an ES6 class based on @Shawn Dotey's answer.
The check()
method does not log a message, but returns the elapsed time.
The method start()
is not needed in his example (the constructor already "starts" it). So I replaced it by reset()
which makes more sense.
export default class TimeCapture
{
constructor()
{
this.reset();
}
reset()
{
this.startTime = new Date().getTime();
this.lastTime = this.startTime;
this.nowTime = this.startTime;
}
check()
{
this.nowTime = new Date().getTime();
const elapsed = this.nowTime - this.lastTime;
this.lastTime = this.nowTime;
return elapsed;
}
}
Use it in your project like this:
import TimeCapture from './time-capture';
const timeCapture = new TimeCapture();
setTimeout(function() {
console.log( timeCapture.check() + " ms have elapsed" ); //~100 ms have elapsed
timeCapture.reset();
setTimeout(function() {
console.log( timeCapture.check() + " ms have elapsed" ); //~200 ms have elapsed
}, 200);
}, 100);