TypingKit
← Code

JavaScript: Debounce a function

Written for TypingKit · ~2 min

0 wpm 100% accuracy 100% real accuracy
export function debounce(fn, wait = 250) {↵
let timer;↵
return function (...args) {↵
clearTimeout(timer);↵
timer = setTimeout(() => fn.apply(this, args), wait);↵
};↵
}↵
↵
const search = debounce((query) => {↵
fetch(`/api/search?q=${encodeURIComponent(query)}`)↵
.then((res) => res.json())↵
.then((results) => render(results));↵
}, 300);