Skip to content

Instantly share code, notes, and snippets.

@bbatsche
Created September 4, 2014 21:00
Show Gist options
  • Save bbatsche/e62165e2aa400a8ce783 to your computer and use it in GitHub Desktop.
Save bbatsche/e62165e2aa400a8ce783 to your computer and use it in GitHub Desktop.
A JavaScript stop watch, demonstrating the use of events, intervals, and querying the DOM
<!DOCTYPE html>
<html>
<head>
<title>Stop Watch</title>
</head>
<body>
<h1>Stop Watch</h1>
<button id="startButton">Start</button>
<button id="stopButton">Stop</button>
<p id="watchValue">0</p>
<script>
var time = 0;
var intervalId;
var startButton = document.getElementById("startButton");
var stopButton = document.getElementById("stopButton");
var startEvent = function() {
time = 0;
intervalId = setInterval(function() {
time++;
document.getElementById("watchValue").innerText = (time / 10);
}, 100);
startButton.removeEventListener("click", startEvent);
};
startButton.addEventListener("click", startEvent);
stopButton.addEventListener("click", function() {
clearInterval(intervalId);
startButton.addEventListener("click", startEvent);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment