How to create a stopwatch using JavaScript?
You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started.
This was a fun little project to work on. Here's how I'd approach it
var Stopwatch = function(elem, options) {
var timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
var a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render(0);
}
function update() {
clock += delta();
render();
}
function render() {
timer.innerHTML = clock / 1000;
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
// public API
this.start = start;
this.stop = stop;
this.reset = reset;
};
// basic examples
var elems = document.getElementsByClassName("basic");
for (var i = 0, len = elems.length; i < len; i++) {
new Stopwatch(elems[i]);
}
// programmatic examples
var a = document.getElementById("a-timer");
aTimer = new Stopwatch(a);
aTimer.start();
var b = document.getElementById("b-timer");
bTimer = new Stopwatch(b, {
delay: 100
});
bTimer.start();
var c = document.getElementById("c-timer");
cTimer = new Stopwatch(c, {
delay: 456
});
cTimer.start();
var d = document.getElementById("d-timer");
dTimer = new Stopwatch(d, {
delay: 1000
});
dTimer.start();
.stopwatch {
display: inline-block;
background-color: white;
border: 1px solid #eee;
padding: 5px;
margin: 5px;
}
.stopwatch span {
font-weight: bold;
display: block;
}
.stopwatch a {
padding-right: 5px;
text-decoration: none;
}
<h2>Basic example; update every 1 ms</h2>
<p>click <code>start</code> to start a stopwatch</p>
<pre>
var elems = document.getElementsByClassName("basic");
for (var i=0, len=elems.length; i<len; i++) {
new Stopwatch(elems[i]);
}
</pre>
<div class="basic stopwatch"></div>
<div class="basic stopwatch"></div>
<hr>
<h2>Programmatic example</h2>
<p><strong>Note:</strong> despite the varying <code>delay</code> settings, each stopwatch displays the correct time (in seconds)</p>
<pre>
var a = document.getElementById("a-timer");
aTimer = new Stopwatch(a);
aTimer.start();
</pre>
<div class="stopwatch" id="a-timer"></div>1 ms<br>
<pre>
var b = document.getElementById("b-timer");
bTimer = new Stopwatch(b, {delay: 100});
bTimer.start();
</pre>
<div class="stopwatch" id="b-timer"></div>100 ms<br>
<pre>
var c = document.getElementById("c-timer");
cTimer = new Stopwatch(c, {delay: 456});
cTimer.start();
</pre>
<div class="stopwatch" id="c-timer"></div>456 ms<br>
<pre>
var d = document.getElementById("d-timer");
dTimer = new Stopwatch(d, {delay: 1000});
dTimer.start();
</pre>
<div class="stopwatch" id="d-timer"></div>1000 ms<br>
How can I create a stopwatch using date.now() in JS?
Here is one I just built, Press "Run code snippet" at the bottom to test it out. Comment if you need further explanation.
var prevTime, stopwatchInterval, elapsedTime = 0;
var updateTime = function () { var tempTime = elapsedTime; var milliseconds = tempTime % 1000; tempTime = Math.floor(tempTime / 1000); var seconds = tempTime % 60; tempTime = Math.floor(tempTime / 60); var minutes = tempTime % 60; tempTime = Math.floor(tempTime / 60); var hours = tempTime % 60; var time = hours + " : " + minutes + " : " + seconds + "." + milliseconds; $("#time").text(time);};
$("#startButton").click(function () { if (!stopwatchInterval) { stopwatchInterval = setInterval(function () { if (!prevTime) { prevTime = Date.now(); } elapsedTime += Date.now() - prevTime; prevTime = Date.now(); updateTime(); }, 50); }});
$("#pauseButton").click(function () { if (stopwatchInterval) { clearInterval(stopwatchInterval); stopwatchInterval = null; } prevTime = null;});
$("#resetButton").click(function () { $("#pauseButton").click(); elapsedTime = 0; updateTime();});
$(document).ready(function () { updateTime();});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Time: <span id="time"></span><br>
<button id="startButton">Start</button><button id="pauseButton">Pause</button><button id="resetButton">Reset</button>
I created a Stopwatch in JavaScript. I would like to add a sound when a user inputs the time to be reminded
First you need inputVal globally as @Denhell mentioned.
var inputVal = Number.POSITIVE_INFINITY;
function getVal(){
inputVal = document.getElementById('inputVal').value;
}
Second your function updateTimer needs a comparison between your inputVal and the actual time of the timer. For playing the sound I transferred your jQuery-code to vanilla JS.function updateTimer() {
if(getTimer() == inputVal){
document.getElementById('ado').play();
pause();
}
}
In the function run the call of the updateTimer has to be executed at the end because otherwise the value for the comparison doesn't function right at the beginning of a new second or minute (e.g. 00:13:00).function run(){
stopwatchEL.textContent = getTimer();
ms++;
if(ms == 100){
ms = 0;
s++;
}
if(s == 60){
s = 0;
m++;
}
updateTimer();
}
The only thing is, that the timer stops right but do not update the last ms. For this you could look yourself. For my solution it is necessary that the manually set time is at the format mm:ss:ms with all three values as a 2-digit value like 01:17:09You can try it here: https://jsfiddle.net/8w67uy5a/5/
Stopwatch in JavaScript
You want a single method to take care of the start/stop:
var startTimer = setInterval(myTimer, 1000),
timerElement = document.getElementById("timer"),
buttonElement = document.getElementById("myButton");
function myTimer(){
var current = new Date();
timerElement.innerHTML = current.toLocaleTimeString();
}
function toggle(){
if (startTimer) {
clearInterval(startTimer);
startTimer = null;
buttonElement.innerHTML = "Start";
} else {
buttonElement.innerHTML = "Stop";
startTimer = setInterval(myTimer, 1000);
}
}
<p id="timer"></p>
<button id="myButton" onclick="toggle()">Stop</button>
How to add lap functionality in stopwatch using Javascript?
Well then, I've edited the code and implemented the lap functionality. Here's what I did.
I would advice you stop using inline html event listeners (onclick)
. So I replaced all the onclicks
with addEventListener('click')
Selecting elements from the DOM is heavy on the performance of your document, so I assigned all the ids
to a variable, because these elements were used a lot.
In the lap function, I used template stings to concatenate the time together, and wrapped them in a <div></div>
tag with a class of lap
in case you want to style the laps later.
I also removed curly braces ({ }
) around one-line ifelse
statements to reduce the number of lines in the code.
You can test it out here in the snippet. :-)
const lapBtn = document.getElementById('lapBtn');
const timerMilliSec = document.getElementById('timerMilliSec');
const timerSec = document.getElementById('timerSec');
const timerMins = document.getElementById('timerMins');
const timerHrs = document.getElementById('timerHrs');
const startBtn = document.getElementById('startBtn');
const resetBtn = document.getElementById('resetBtn');
const lapRecord = document.getElementById('lapRecord');
let hours = 0;
let minutes = 0;
let seconds = 0;
let miliseconds = 0;
let displayMilisec = miliseconds;
let displaySec = seconds;
let displayMins = minutes;
let displayHours = hours;
let interval = null;
let status = "stopped";
let lapNow = null;
function start() {
miliseconds++;
if (miliseconds < 10) displayMilisec = "0" + miliseconds.toString();
else displayMilisec = miliseconds;
if (seconds < 10) displaySec = "0" + seconds.toString();
else displaySec = seconds;
if (minutes < 10) displayMins = "0" + minutes.toString();
else displayMins = minutes;
if (hours < 10) displayHours = "0" + hours.toString();
else displayHours = hours;
if (miliseconds / 100 === 1) {
seconds++;
miliseconds = 0;
if (seconds / 60 === 1) {
minutes++;
seconds = 0;
if (minutes / 60 === 1) {
hours++;
minutes = 0;
}
}
}
timerMilisec.innerHTML = displayMilisec;
timerSec.innerHTML = displaySec;
timerMins.innerHTML = displayMins;
timerHrs.innerHTML = displayHours;
}
function startStop() {
if (status === "stopped") {
interval = setInterval(start, 10);
startBtn.innerHTML = "Stop";
status = "started";
} else {
clearInterval(interval);
startBtn.innerHTML = "Start";
status = "stopped";
}
}
function reset() {
clearInterval(interval);
miliseconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
timerMilisec.innerHTML = "00";
timerSec.innerHTML = "00";
timerMins.innerHTML = "00";
timerHrs.innerHTML = "00";
startBtn.innerHTML = "Start";
lapRecord.innerHTML = '';
status = "stopped";
}
function lap() {
lapNow = `<div class="lap">${hours} : ${minutes} : ${seconds} : ${miliseconds}</div>`;
lapRecord.innerHTML += lapNow;
}
lapBtn.addEventListener('click', lap);
startBtn.addEventListener('click', startStop);
resetBtn.addEventListener('click', reset);
body {
height: 100vh;
margin: 40px 0px 0px 0px;
background-color: #58e065;
display: flex;
justify-content: center;
overflow: hidden;
}
.display {
display: flex;
left: 50%;
align-items: center;
justify-content: center;
font-family: "nunito", "poppins", sans-serif;
font-weight: 700;
font-size: 60px;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
}
p {
margin: 5px;
}
.buttons {
display: flex;
justify-content: center;
}
button {
cursor: pointer;
height: 30px;
width: 80px;
border: none;
outline: none;
border-radius: 4px;
background-color: #3b85ed;
font-family: "nunito", "poppins", sans-serif;
font-size: 18px;
font-weight: 700;
color: white;
box-shadow: 3px 3px 0px #224f8f;
margin: 4px;
}
button:hover {
background-color: #224f8f;
}
h1 {
position: sticky;
background-color: #ff961d;
display: flex;
justify-content: center;
margin: 30px;
font-family: "nunito", "poppins", sans-serif;
font-size: 40px;
font-weight: 700;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
border-radius: 10px;
box-shadow: 3px 3px 0px rgb(179, 101, 0);
}
#header {
width: 100%;
height: 100px;
position: sticky;
}
#laps {
margin-top: 40px;
height: 400px;
scroll-behavior: smooth;
}
<div class="wrapper" id="wrapper">
<div class="display">
<p class="timerDisplay" id="timerHrs">00</p> :
<p class="timerDisplay" id="timerMins">00</p> :
<p class="timerDisplay" id="timerSec">00</p> :
<p class="timerDisplay" id="timerMilisec">00</p>
</div>
<div class="buttons">
<button type="button" id="startBtn">Start</button>
<button type="button" id="resetBtn">Reset</button>
<button type="button" id="lapBtn">Lap</button>
</div>
<h1>Laps:</h1>
<div id="laps">
<p id="lapRecord"></p>
</div>
</div>
Related Topics
Load Local JSON File into Variable
How to Create a Date Object from String in JavaScript
Loading Backbone and Underscore Using Requirejs
JavaScript Settimeout and Loops
What Is the 'Execution Context' in JavaScript Exactly
D3.JSON Method Doesn't Return My Data Array
Do Browsers Parse JavaScript on Every Page Load
Why Does JavaScript's Regex.Exec() Not Always Return the Same Value
Angular 2.1.0 Create Child Component on the Fly, Dynamically
How to Pass a Flag to Gulp to Have It Run Tasks in Different Ways
How to Get Month and Date of JavaScript in 2 Digit Format
Differencebetween Decodeuricomponent and Decodeuri
JavaScript Mapping Touch Events to Mouse Events
Omitting the Second Expression When Using the If-Else Shorthand
Why Do People Put Code Like "Throw 1; <Dont Be Evil>" and "For(;;);" in Front of JSON Responses
How to Export Socket.Io into Other Modules in Nodejs
Get Visitors Language & Country Code with JavaScript (Client-Side)