Complete the code to create a timer that repeats every second.
setInterval(() => { console.log('Tick'); }, [1]);The setInterval function takes the delay in milliseconds. 1000 ms means 1 second.
Complete the code to remove the event listener properly.
emitter.on('data', handler); // Later remove listener emitter.[1]('data', handler);
addListener again adds more listeners, causing leaks.emit triggers events but does not remove listeners.To avoid memory leaks, remove event listeners with removeListener when no longer needed.
Fix the error in the code to avoid a memory leak caused by global variables.
global.cache = {};
function addToCache(key, value) {
[1].cache[key] = value;
}window causes errors because it is a browser object.this may not refer to the global object here.In Node.js, global is the global object. Using it explicitly avoids confusion and leaks.
Fill both blanks to create a WeakMap and store an object without preventing garbage collection.
const cache = new [1](); const obj = {}; cache.[2](obj, 'data');
Map keeps strong references, causing leaks.add is not a method of Map or WeakMap.A WeakMap allows objects to be garbage collected if no other references exist. Use set to add entries.
Fill all three blanks to create a closure that does not cause a memory leak by holding unnecessary references.
function createCounter() {
let count = 0;
return function() {
count [1] 1;
return [2];
};
}
const counter = createCounter();
counter(); // [3]++ alone without return causes confusion.1 always does not reflect the count.Use count += 1 to increment, return count, and calling counter() returns 1.