Languages
[Edit]
EN

JavaScript - how to make stopwatch?

10 points
Created by:
JustMike
3491

In JavaScript it is possible to make stopwatch in following way.

1. Custom stopwatch example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script>

    function calculatePeriod(t1, t2) {
        var dt = t2 - t1;

        var units = [
            {name: 'milliseconds', scale: 1000},
            {name: 'seconds', scale: 60},
            {name: 'minutes', scale: 60},
            {name: 'hours', scale: 24}
        ];

        var result = { };

        for(var i = 0; i < units.length; ++i) {
            var unit = units[i];

            var total = Math.floor(dt / unit.scale);
            var rest = dt - total * unit.scale;

            result[unit.name] = rest;

            dt = total;
        }

        result.days = dt;

        return result;
    }

    function padLeft(number, length, character) {
        if(character == null)
            character = '0';

        var result = number.toString();

        for(var i = result.length; i < length; ++i) {
            result = character + result;
        }

        return result;
    }

  </script>
</head>
<body>
  <div id="display">00:00:00.000</div>
  <button onclick="startStopwatch();">Start</button>
  <button onclick="stopStopwatch();">Stop</button>
  <script>

	var interval = null;
	var display = document.getElementById('display');
    
    function startStopwatch() {
    	if(interval)
          	return;

      	var start = new Date();
      
      	function tick() {
        	var now = new Date();
          	var period = calculatePeriod(start, now);

          	var text = '';
          
          	if (period.days) {
            	text += padLeft(period.days, 2) + ' days ';
            }
          
          	text += padLeft(period.hours, 2) + ':';
          	text += padLeft(period.minutes, 2) + ':';
          	text += padLeft(period.seconds, 2) + '.';
          	text += padLeft(period.milliseconds, 3);
          
          	display.innerText = text;
        }
      
      	interval = setInterval(tick, 10); // once per 10 ms
    }
    
    function stopStopwatch() {
    	if(interval) {
        	clearInterval(interval);

          	interval = null;
        }
    }

  </script>
</body>
</html>

See also

  1. JavaScript - how to calculate time period (time difference in days, minutes, seconds and milliseconds)?

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.