Skip to content

Instantly share code, notes, and snippets.

@azu
Last active June 1, 2021 07:16
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azu/d7942102dc5282b0eca859149791c3f0 to your computer and use it in GitHub Desktop.
Save azu/d7942102dc5282b0eca859149791c3f0 to your computer and use it in GitHub Desktop.
Logging Timer and requestAnimationFrame
/**
* ## Usage
*
* 1. Load following script
* 2. `window.getContexualLogResult()` output the result to console
*
* ## Description
*
* - It spy "setTimeout", "setInterval", and "requestAnimationFrame".
* - Collect call count and collect stack trace.
*/
// Disapprear log less than 5
const thresholdCount = 5;
const map = new Map([
["setTimeout", {}],
["setInterval", {}],
["requestAnimationFrame", {}]
]);
window.getContexualLogResult = () => {
["setTimeout", "setInterval", "requestAnimationFrame"].forEach(name => {
const result = Object.entries(map.get(name))
.filter(entry => {
return entry[1] > thresholdCount;
}).map(entry => {
return {
code: entry[0],
count: entry[1]
}
});
console.group(name);
console.table(result);
console.groupEnd(name);
});
}
const contexualLog = (type, log) => {
if (map.has(type)) {
const object = map.get(type);
const count = object[log] ? object[log] : 0;
object[log] = count + 1;
} else {
const object = {};
const count = object[log] ? object[log] : 0;
object[log] = count + 1;
map.set(type, object);
}
}
const originalTimout = window.setTimeout;
window.setTimeout = function () {
const stack = (new Error().stack).split("\n").slice(1);
if (arguments.callee.caller) {
contexualLog("setTimeout", arguments.callee.caller.toString() + "\n" + stack);
} else {
contexualLog("setInterval", stack)
}
return originalTimout.apply(window, arguments);
}
const originalInterval = window.setInterval;
window.setInterval = function () {
const stack = (new Error().stack).split("\n").slice(1).join("\n");
if (arguments.callee.caller) {
contexualLog("setInterval", arguments.callee.caller.toString() + "\n" + stack);
} else {
contexualLog("setInterval", stack)
}
return originalInterval.apply(window, arguments);
}
const originalRaF = window.requestAnimationFrame;
window.requestAnimationFrame = function (callback) {
const stack = (new Error().stack).split("\n").slice(1).join("\n");
if (arguments.callee.caller) {
contexualLog("requestAnimationFrame", arguments.callee.caller.toString() + "\n" + stack);
} else {
contexualLog("requestAnimationFrame", stack)
}
return originalRaF(callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment