Skip to content

Instantly share code, notes, and snippets.

@likev
Created October 9, 2021 06:37
Show Gist options
  • Save likev/0f3e24e4750cd14e0ed13d673bc7af16 to your computer and use it in GitHub Desktop.
Save likev/0f3e24e4750cd14e0ed13d673bc7af16 to your computer and use it in GitHub Desktop.
js closure memory leak and fix demo
function test() {
//very long string
let s = new Array(1000 * 500).join(new Array(1000).join('x'));
window.check = function() {}//closure
let out = setTimeout(_ => {
if (window.check) {
//random index
let i = Math.round(Math.random() * 5E5);
console.log(s[i])
//s = null //fix memory leak
}
clearTimeout(out)
}, 5 * 1000)
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment