Skip to content

Instantly share code, notes, and snippets.

@NealEhardt
Last active November 6, 2020 21:58
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 NealEhardt/176ed99e3cebe145a8993e5448f6c099 to your computer and use it in GitHub Desktop.
Save NealEhardt/176ed99e3cebe145a8993e5448f6c099 to your computer and use it in GitHub Desktop.
Instrumentation for the event loop
/*
Paste this script in the console of a live website to quantify its lag.
This script calls `setTimeout` every 50ms. If the event loop takes more than 2x that long
to hit the callback, it's considered lag.
Consecutive laggy loops are counted together and then, after the lag passes, they are
logged to the console as a single warning.
Like this:
Lagged for 254 ms over 2 loop(s). Should have taken 100 ms (39% of actual).
*/
(function (timeoutDurationMs) {
var lastQuickDate = null, lastDate = null, loopsSinceLastQuickDate = 0;
function testTimeout() {
var d = new Date();
if (!lastQuickDate) {
lastQuickDate = lastDate = d;
}
if (d - lastDate < timeoutDurationMs * 2) {
if (lastDate !== lastQuickDate) {
var slowdown = lastDate - lastQuickDate;
var expectedTime = loopsSinceLastQuickDate * timeoutDurationMs;
var percent = Math.round(expectedTime / slowdown * 100);
console.warn('Lagged for ' + slowdown + ' ms over ' + loopsSinceLastQuickDate
+ ' loop(s). Should have taken ' + expectedTime + ' ms (' + percent + '% of actual).');
}
lastQuickDate = d;
loopsSinceLastQuickDate = 0;
} else {
loopsSinceLastQuickDate++;
}
lastDate = d;
setTimeout(testTimeout, timeoutDurationMs);
}
testTimeout();
return 'Okay';
})(50);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment