Published on

Debounce in JavaScript


utils/debounce.js
const debounce = (func, duration = 2000) => {
	let timeout;

	return function(...args) {
		const effect = () => {
			timeout = null;
			return func.apply(this, args)
		}

		clearTimeout(timeout);
		timeout = setTimeout(effect, duration);
	}
}

export default debounce;

Usage

import debounce from 'utils/debounce'

const handler = debounce(() => console.log('I will print after 4 seconds'), 4000)

Output

Output for debounce
Output for debounce

Updates straight in your inbox!

A periodic update about my life, recent blog posts, TIL (Today I learned) related stuff, things I am building and more!

Share with others