Last active
November 6, 2020 21:58
-
-
Save NealEhardt/176ed99e3cebe145a8993e5448f6c099 to your computer and use it in GitHub Desktop.
Instrumentation for the event loop
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
/* | |
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