const debounce = (callback, ms) => {
let timeoutId = null;
return function(...args) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
timeoutId = setTimeout(() => callback(...args), ms);
};
};
const log = () => console.log('вызвано!');
// const debouncedLog = debounce(log, 10000);
// debouncedLog(); // старт таймера
// debouncedLog(); // сброс, старт заново
// debouncedLog(); // сброс, старт заново
const throttle = (fn, ms) => {
let timeoutId = null;
return function(...args) {
if (!timeoutId) {
fn(...args);
}
timeoutId = setTimeout(() => {
clearTimeout(timeoutId);
timeoutId = null;
}, ms);
};
};
const throttledLog = throttle(log, 300);
throttledLog(); // выполнится сразу: "вызвано!"
throttledLog(); // проигнорирован (внутри интервала)
throttledLog(); // проигнорирован
// через 300мс — интервал закончился
setTimeout(() => throttledLog(), 300);
throttledLog(); // выполнится: "вызвано!"
Click Run to execute JavaScript.
Code runs in an isolated environment.
Code runs in an isolated environment.