Reputation: 323
I'm trying to create a timer similar to the one on qqtimer.net The behavior of the timer is as follows:
and so on and so forth. From my research, it seems the best way to do this is with setInterval
and document.onkeypress
. Here's my code so far:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="main.js">
</script>
</head>
<body>
<div id="timer">
0
</div>
</body>
</html>
main.js
var running = false;
document.onkeypress = function(e) {
if (e.keyCode === 0 || e.keyCode === 32) {
if (running) {
clearInterval(refresh);
} else {
var startTime = new Date().getTime();
var refresh = window.setInterval(function() {
document.getElementById('timer').innerHTML = new Date().getTime() - startTime;
}, 100);
}
}
};
This code works fine for the timer starting, but stopping it doesn't seem to work. It never ends the original setInterval
, so the third space press starts another setInterval
at the same time.
Multiple guides I've looked at say that clearInterval(refresh)
should stop the interval, but that doesn't seem to be true.
What do I need to change to fix this?
Upvotes: 0
Views: 53
Reputation: 2742
The main reason was that you were declaring refresh inside of the if statment, so it was unavailable when you tried to clear it. Check out this working example below.
var running = false;
var refresh;
document.onkeypress = function(e) {
if (e.keyCode === 0 || e.keyCode === 32) {
if (running) {
clearInterval(refresh);
running = false;
} else {
var startTime = new Date().getTime();
refresh = setInterval(function() {
document.getElementById('timer').innerHTML = new Date().getTime() - startTime;
}, 100);
running = true;
}
}
};
Upvotes: 2