Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch: debounce restart in watch mode #51971

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion lib/internal/main/watch_mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
ArrayPrototypeMap,
ArrayPrototypePushApply,
ArrayPrototypeSlice,
PromiseResolve,
StringPrototypeStartsWith,
} = primordials;

Expand Down Expand Up @@ -110,16 +111,62 @@ async function restart() {
start();
}

function debounce(fn, delay) {
let state = 'idle';
let timer;
let promise = PromiseResolve();

const afterDelay = () => {
state = 'running';
promise = promise
.then(() => fn())
.catch((error) => {
triggerUncaughtException(error, true /* fromPromise */);
})
.finally(() => {
if (state === 'running') {
state = 'idle';
} else if (state === 'pending') {
state = 'debouncing';
timer = setTimeout(afterDelay, delay);
}
});
};

return debouncedFn;

function debouncedFn(destroy = false) {
if (destroy) {
clearTimeout(timer);
state = 'destroyed';
} else if (state === 'idle') {
state = 'debouncing';
timer = setTimeout(afterDelay, delay);
} else if (state === 'debouncing') {
clearTimeout(timer);
timer = setTimeout(afterDelay, delay);
} else if (state === 'running') {
state = 'pending';
}

return promise;
}
}

(async () => {
emitExperimentalWarning('Watch mode');

try {
start();

const debouncedRestart = debounce(restart, 200);

// eslint-disable-next-line no-unused-vars
for await (const _ of on(watcher, 'changed')) {
await restart();
debouncedRestart();
}

await debouncedRestart(true);
} catch (error) {
triggerUncaughtException(error, true /* fromPromise */);
}
Expand Down
Loading