Timeout Wrapper Timer Leak
A Promise.race timeout helper looks correct but leaks a timer that keeps firing after the race is decided.
Codejavascript
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error('timeout')), ms);
});
return Promise.race([promise, timeout]);
}
// usage
const data = await withTimeout(fetchData(), 3000);This wrapper resolves/rejects correctly in the happy path, but it has a real resource/cleanup bug. What is it and how do you fix it?