Languages
[Edit]
EN

JavaScript - how to make stopwatch with split time feature?

13 points
Created by:
Root-ssh
68980

In JavaScript it is possible to make stopwatch with lap time feature in following way.

1. Custom stopwatch example

This section shows how to write custom stopwatch.

Screenshots:

Custom stopwatch is run - JavaScript
Custom stopwatch is run - JavaScript
Custom stopwatch with time splitting (many time laps) - JavaScript
Custom stopwatch with time splitting (many time laps) - JavaScript

We have 3 buttons - Start, Stop, Split time. Play with this example to see how it works.

Run below code by clicking on Run button.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    #display, #times {
      	margin: 10px 0px;
    	padding: 10px;
      	border: 1px solid silver;
    	font-family: monospace;
    }
    
    .total-time { /* total measured time */
    	font-size: 30px;
    }
    
    .split-time { /* time of last split */
    	font-size: 15px;
    }
    
    button {
      	margin: 0px;
    	padding: 5px;
    }
    
  </style>
  <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;
    }
    
    function renderTime(t1, t2) {
    	var period = calculatePeriod(t1, t2);

        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);

        return text;
    }

  </script>
</head>
<body>
  <div id="display">
    <div class="total-time">
      00:00:00.000
    </div>
  </div>
  <button onclick="startStopwatch();">Start</button>
  <button onclick="stopStopwatch();">Stop</button>
  <button onclick="splitTime();">Split time</button>
  <div id="times" style="display: none;"></div>
  <script>

	var interval = null; // interval id
    
    var start = null; // start time
    var split = null; // split time
    
	var display = document.getElementById('display');
	var times = document.getElementById('times');

    function startStopwatch() {
    	if(interval)
          	return;

      	start = new Date();
      
      	if(split) {
          	times.style.display = 'none';
          	times.innerHTML = '';
          
        	split = null;
        }
      
      	function tick() {
        	var now = new Date();
          	
          	if(split) {
            	var html = '<div class="total-time">' 
                	+ renderTime(start, now) 
                	+ '</div>'
                	+ '<div class="split-time">' 
                	+ renderTime(split, now)
                	+ '</div>';
              
              	display.innerHTML = html;
            } else {
            	var html = '<div class="total-time">' 
                	+ renderTime(start, now) 
                	+ '</div>';
              
              	display.innerHTML = html;
            }
        }
      
      	interval = setInterval(tick, 10); // once per 10 ms
    }
    
    function stopStopwatch() {
    	if(interval) {
        	clearInterval(interval);

          	interval = null;
        }
    }
    
    function splitTime() {
    	if(interval) {
         	var now = new Date();

          	if (split == null) {
                times.innerHTML += '<div class="split-time">' 
                    + renderTime(start, now)
                    + '</div>';
              
            	times.style.display = 'block';
            } else {
            	times.innerHTML += '<div class="split-time">' 
                    + renderTime(split, now)
                    + '</div>';
            }
 
          	split = now;
        }
    }

  </script>
</body>
</html>
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join