Skip to content

Instantly share code, notes, and snippets.

@Herst
Last active November 12, 2017 13:39
Show Gist options
  • Save Herst/f40207373c9f983cfba2e79442b51129 to your computer and use it in GitHub Desktop.
Save Herst/f40207373c9f983cfba2e79442b51129 to your computer and use it in GitHub Desktop.
setTimeout/setInterval experiment involving slow-downs
license: gpl-3.0

setTimeout vs. setInterval experiment involving slow-downs.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<select id="selectMethod">
<option selected></option>
<option>setTimeout</option>
<option>setInterval</option>
</select>
<label><input type="checkbox" id="cbSlowDown">Make function execution take longer than time for a tick</label>
<p>Counter: <span id="counter">0</span></p>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
const TIME = 500;
const SLOWDOWN_RATE = 2;
var setIntervalCounter = d3.select("#counter");
var count = 0.0;
var ts = Date.now();
var slowDown = false;
var timer;
function tick() {
setIntervalCounter.text(count += .5);
while (slowDown && (ts + TIME * SLOWDOWN_RATE) > Date.now());
ts = Date.now();
}
function changeMethod(method) {
clearTimeout(timer);
switch (method) {
case "setTimeout":
timer = window.setTimeout(function fun() {
tick();
timer = window.setTimeout(fun, TIME);
}, TIME);
break;
case "setInterval":
timer = window.setInterval(tick, TIME);
break;
}
}
d3.select("#selectMethod").on("change", function () {
changeMethod(this.value);
});
d3.select("#cbSlowDown").on("change", function () {
slowDown = this.checked;
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment