Skip to content

Instantly share code, notes, and snippets.

@qnighy
Created October 7, 2022 06:31
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 qnighy/898b76c0fb3369e013814c66c5fabaad to your computer and use it in GitHub Desktop.
Save qnighy/898b76c0fb3369e013814c66c5fabaad to your computer and use it in GitHub Desktop.
Test how a browser throttles setTimeout/setInterval
<!doctype html>
<html>
<head>
<script type="module">
const segment = 10000;
const num_segments = 6;
const retain = segment * num_segments;
let dateHistory = [];
function getEstimates() {
const current = dateHistory[dateHistory.length - 1];
const estimates = [];
let j = dateHistory.length - 1;
for (let i = 0; i < num_segments; i++) {
const j_last = j;
while (j > 0 && dateHistory[j - 1] >= current - segment * (i + 1)) {
j--;
}
estimates.push((dateHistory[j_last] - dateHistory[j]) / (j_last - j));
}
return estimates;
}
function tick() {
const current = Number(new Date());
dateHistory.push(current);
while (dateHistory.length > 0 && dateHistory[0] < current - retain) {
dateHistory.shift();
}
const estimates = getEstimates();
document.querySelector("#estim").innerHTML = estimates.join("<br>");
}
let interval = setInterval(tick, 300);
document.querySelector("#interval").addEventListener("change", () => {
const newTick = Number(document.querySelector("#interval").value);
clearInterval(interval);
interval = setInterval(tick, newTick);
});
</script>
</head>
<body>
<p id="estim"></p>
<select id="interval">
<option value="30">30ms</option>
<option value="300" selected>300ms</option>
<option value="1000">1000ms</option>
<option value="3000">3000ms</option>
</select>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment