Created
October 7, 2022 06:31
-
-
Save qnighy/898b76c0fb3369e013814c66c5fabaad to your computer and use it in GitHub Desktop.
Test how a browser throttles setTimeout/setInterval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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