Created
November 7, 2019 20:28
-
-
Save omrilotan/c8775a51090af67d48d9e07301c955fb to your computer and use it in GitHub Desktop.
Monitor heap usage of a web page. Throw error when heap exceeds its limitations.
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
function monitorHeap({MAX_BYTES = 100, MAX_PERCENT = 90} = {}) { | |
if (!window.performance || !window.performance.memory || !window.requestAnimationFrame) { return; } | |
const MB = 1048576; | |
const MAX_MEMORY = MAX_BYTES * MB; | |
const MAX_PERCENTILE = MAX_PERCENT / 100; | |
function heapcop() { | |
const { usedJSHeapSize, jsHeapSizeLimit } = performance.memory; | |
// Check if we've exceeded absolute memory limit | |
if (usedJSHeapSize > MAX_MEMORY) { | |
const error = new Error(`Exceeded memory maximum limit (${MAX_BYTES})`); | |
error.code = 'EXCEEDED_MEMORY_ERROR'; | |
error.details = { used_heap_size: Math.round(usedJSHeapSize / MB) }; | |
throw error; | |
} | |
// Check if we've exceeded relative memory limit for client | |
if (usedJSHeapSize > MAX_PERCENTILE * jsHeapSizeLimit) { | |
const limit = Math.round(jsHeapSizeLimit / MB); | |
const error = new Error(`Memory usage exceeded ${100 * MAX_PERCENT}% of ${limit}MB`); | |
error.code = 'EXCEEDED_MEMORY_ERROR'; | |
error.details = { | |
used_heap_size: Math.round(usedJSHeapSize / MB), | |
heap_size_limit: limit | |
}; | |
throw error; | |
} | |
// Only alert once | |
requestAnimationFrame(heapcop); | |
} | |
requestAnimationFrame(heapcop); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment