Roadmap › JavaScript (ES5 → ES2025) & TypeScript Basics › Module: Browser and DOM
Lessons in this course (16)
13. Debounce, throttle, memoisation and other utilities
Intermediate★ Must knowLesson 13 of 16
js
function debounce(fn, ms) { // run after the user STOPS for ms (search box)
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), ms);
};
}
function throttle(fn, ms) { // run at most once per ms (scroll, resize)
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= ms) { last = now; fn.apply(this, args); }
};
}
function memoize(fn) {
const cache = new Map();
return arg => cache.has(arg) ? cache.get(arg) : (cache.set(arg, fn(arg)), cache.get(arg));
}
const curry = fn => function curried(...args) {
return args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);
};