How to calculate a duration time in JavaScript?

One of the simplest way to do this is to create two dates and just subtract them.

    var date1 = new Date();
    var date2 = new Date();
    var duration = date2 - date1;


Make a simple stopwatch and calculate the duration time in JavaScript.

<div id="stopwatch">
    <button onmousedown="start()" id="startButton">Start</button>

<div id="result">Waiting...</div>

    var date = new Date();

    function start() {
        document.getElementById('stopwatch').innerHTML = '<button onmousedown="stop()" id="stopButton">Stop</button>'
        date = new Date();

        document.getElementById('result').innerHTML = 'Click "Stop" when you are ready.';

    function stop() {
        document.getElementById('stopwatch').innerHTML = '<button onmousedown="start()" id="startButton">Start</button>'
        var date2 = new Date();
        var result = date2 - date;
        document.getElementById('result').innerHTML = '<b>Result:</b> ' + result + ' ms';