function debounce(fn, ms, immediate) {
let timer;
let isWaiting = false;
return function(...args) {
const context = this;
clearTimeout(timer);
if (immediate && !isWaiting) {
fn.apply(context, args);
isWaiting = true;
}
timer = setTimeout(() => {
isWaiting = true;
}, ms);
};
}
 
const d = debounce(x => console.log(x), 1000, true);
 
d('A'); // сразу печатает A
d('B'); // тишина
d('C'); // тишина
// через секунду тишины блокировка снимается
 
setTimeout(() => d('D'), 2000); // сразу печатает D
 
const d2 = debounce(x => console.log(x), 1000, false);
d2('X'); // должно напечатать X через секунду
 
Code will run automatically after changes.
Code runs in an isolated environment.