Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - how to make stopwatch with split time feature?

0 contributions
13 points

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

1. Custom stopwatch example

By executing below code we will get:

After we click on Split time couple of times we will get:

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

 

Run below example 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>

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more