1.0.8 • Published 4 years ago

mini-debounce v1.0.8

Weekly downloads
14
License
MIT
Repository
github
Last release
4 years ago

mini-debounce

An extremely small and modern debounce library that is supported by all major browsers.

mini-debounce is only 94 bytes, that's smaller than tiny-debounce by 161 bytes!!!

Installation:

yarn add mini-debounce
# or
npm install mini-debounce

Usage:

Arguments

NameTypeDescription
callbackFunctionThe function to be debounced
timeoutnumberThe number of milliseconds to wait after called

Returns

TypeDescription
FunctionReturns the new debounced function, once called the previous timeout is cancelled and a new timeout is initiated

"Okay but what does that function return?"

It returns the id from setTimeout which allows you to run clearTimeout in order to cancel the debounced call.

First let's import it

The function is not exported as default as to provide better intellisense.

import {debounce} from 'mini-debounce'
// or
const {debounce} = require('mini-debounce')

Now let's use it:

// Create the debounced function
const debouncedLog = debounce(x => console.log('[LOG]', x), 1000)

// Use it
debouncedLog('Hello...')
debouncedLog("It's me")
debouncedLog('I was wondering')
debouncedLog('if after all')

// 1000 milliseconds later
// => "[LOG] if after all"

// You can cancel them as well
const id = debouncedLog('This will never appear')
clearTimeout(id)

How about in a React component

Here we'll demonstrate an implementation of a debounced search input.

class Search {
	state = {query: ''}

	search = debounce(query => {
		/* this will only be run 1000 milliseconds after no changes */
		fetch(`https://example.com/api?q=${query}`).then(/* do whatever */)
	}, 1000)

	handleChange = event => {
		const query = event.target.value

		this.setState({query})
		this.search(query)
	}

	render() {
		return <input value={this.state.query} onChange={this.handleChange} />
	}
}
// Now as a function
function Search() {
	const [query, setQuery] = useState('')

	const search = debounce(query => {
		fetch(/* you know */).then(/* do whatever */)
	}, 1000)

	function handleChange(event) {
		const query = event.target.value

		setQuery(query)
		search(query)
	}

	return <input value={query} onChange={handleChange} />
}

License

MIT License Copyright © 2019 Christopher Holden Brown