How to debounce / throttle with Svelte?
It's the method itself that should be debounced — so rather than calling debounce
on each input event, set handleInput
up to be a debounced method:
<div>
<input on:input="handleInput(event)">
</div>
<script>
import { debounce } from 'lodash'
export default {
data () {
return { name: '' };
},
methods: {
handleInput: debounce (async function (event) {
this.set({ name: await apiCall(event.target.value).response.name })
}, 300)
}
}
</script>
Simplified REPL example here.
EDIT: svelte v3 version
<input on:input={handleInput}>
<script>
import debounce from 'lodash/debounce'
let name = '';
const handleInput = debounce(e => {
name = e.target.value;
}, 300)
</script>
REPL example here.