setInterval dropped frames
If a tab loses focus, setInterval callbacks are lost.
by mendesjuan
HTML
<div class=sticky>
This page is logging the current timestamp every 100 ms. Send this tab to the background and it will be obvious that setInterval is not being called when the window doesn't have focus and that some calls are being droped because <code>timeSinceStart</code> should be roughly <code>(iteration + 1) * <span id="intervalMs">100</span></code>
<hr />
<button type="button" onclick="clearInterval(window.interval);">Stop Interval</button>
<button type="button" onclick="window.shouldScroll=false">Stop Scrolling</button>
<button type="button" onclick="window.shouldScroll=true">Start Scrolling</button>
</div>
CSS
div.sticky {
position: sticky;
top: 0px;
background-color: #eee;
}
JavaScript
let iteration = 0;
const startTime = +new Date();
// Change this to try different intervals
const intervalMs = 100;
window.shouldScroll = true;
document.getElementById("intervalMs").innerText = intervalMs;
window.interval = setInterval(() => {
const node = document.createElement("div");
const now = +new Date();
const sinceStart = now - startTime;
node.innerHTML = JSON.stringify({
iteration: ++iteration,
sinceStart,
expectedSinceStart: `~${iteration * intervalMs}`
}) + "<hr />"
document.body.appendChild(node);
if (window.shouldScroll) {
window.scrollTo(0, document.body.scrollHeight);
}
}, 100)