So i currently have:
App.html
<div>
<input on:input="debounce(handleInput, 300)">
</div>
<script>
import { debounce } from 'lodash'
export default {
data () {
name: ''
},
methods: {
debounce,
async handleInput (event) {
this.set({ name: await apiCall(event.target.value).response.name })
}
}
}
</script>
And get the error Uncaught TypeError: Expected a function at App.debounce
. This comes from Lodash so it doesn't seem like the method from Svelte is being passed through.
Extra extra edit
Extra context for how i'm currently achieving it:
oncreate () {
const debounceFnc = this.handleInput.bind(this)
this.refs.search.addEventListener('input', debounce(debounceFnc, 300))
}
It's simple. They do the exact same thing (rate limiting) except while throttle is being called it'll fire your function periodically, while debounce only fires once at the end. Example: If you're scrolling, throttle will slowly call your function while you scroll (every X milliseconds).
In JavaScript, a debounce function makes sure that your code is only triggered once per user input. Search box suggestions, text-field auto-saves, and eliminating double-button clicks are all use cases for debounce. In this tutorial, we'll learn how to create a debounce function in JavaScript.
What is debounce? Debounce delays the processing of a function bound to a certain user input event until a certain amount of time has passed. In other words the function is only executed once per specific user input event, even it the event is triggered multiple times.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With