rogerpence.com

A nerd's blog

A simple JavaScript stopwatch

Posted on: Tuesday, Dec 05, 2017

It's good have some metrics backed into APIs and other parts of your code. This simple little JavaScript object lets you easily capture the elapsed time in milliseconds.

StopWatch = function()
{
    this.StartMilliseconds = 0;
    this.ElapsedMilliseconds = 0;
}  

StopWatch.prototype.Start = function()
{
    this.StartMilliseconds = new Date().getTime();
}

StopWatch.prototype.Stop = function()
{
    this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}

Consume the StopWatch class like this:

let s1 = new StopWatch();
s1.Start();        
// Do something.
s1.Stop();
console.log(s1.ElapsedMilliseconds);

Add your comment

You email is never shared with anyone else.

© Copyright 2017 by Roger Pence. All rights reserved.