Skip to content

Instantly share code, notes, and snippets.

@doup
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doup/11248993 to your computer and use it in GitHub Desktop.
Save doup/11248993 to your computer and use it in GitHub Desktop.
Answer to StackOverflow question: "SetInterval(), ClearInterval() timer questions for javascript" – http://stackoverflow.com/questions/23257873/setinterval-clearinterval-timer-questions-for-javascript/23258830#23258830
$(function () {
var rounds = 3;
var states = ['work', 'rest', 'wait'];
var lengths = [3, 1, 2]; // In seconds
var start = $('#start');
var stop = $('#stop');
var stats = $('#stats');
var roundEl = $('#round');
var stateEl = $('#state');
var cronoEl = $('#crono');
var timer;
start.click(function () {
var ctimer, date;
// UI
start.prop('disabled', true);
stop.prop('disabled', false);
stats.show();
// Start round
nextRound(0);
function nextRound(round) {
// Update UI
roundEl.html(round + 1);
if (round < rounds) {
// Start new round
nextState(round, 0);
} else {
// We have finished
stop.click();
}
}
function nextState(round, state) {
if (state < states.length) {
stateEl.html(states[state]);
// Start crono UI
time = new Date();
ctimer = setInterval(crono, 15);
// State timer
timer = setTimeout(function () {
clearInterval(ctimer);
nextState(round, state + 1);
}, lengths[state] * 1000);
} else {
nextRound(round + 1);
}
}
function crono() {
cronoEl.html((((new Date()).getTime() - time.getTime()) / 1000).toFixed(2));
}
});
stop.click(function () {
clearTimeout(timer);
start.prop('disabled', false);
stop.prop('disabled', true);
stats.hide();
});
});
<html>
<head>
<style>
.stats {
font-family: Helvetica Neue;
font-size: 40px;
}
.stats .state {
text-transform: uppercase;
}
</style>
</head>
<body>
<input id="start" value="START" type="button" />
<input id="stop" value="STOP" type="button" disabled />
<div id="stats" class="stats" style="display:none;">
Round: <span id="round"></span><br>
State: <span id="state" class="state"></span><br>
Time: <span id="crono"></span>s<br>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment