Skip to content

Instantly share code, notes, and snippets.

@alexnoz
Created June 13, 2018 20:11
Show Gist options
  • Save alexnoz/0352bdd1b92ea2d50f7eddb890de71fe to your computer and use it in GitHub Desktop.
Save alexnoz/0352bdd1b92ea2d50f7eddb890de71fe to your computer and use it in GitHub Desktop.
Abort fetching data in a function when debouncing it
function debounceFetch (fn, delay, onCancel = () => {}) {
let timer = 0, isFetching = false
return function (...args) {
clearTimeout(timer)
if (isFetching) {
onCancel()
isFetching = false
}
timer = setTimeout(() => {
isFetching = true
fn(...args)
}, delay)
}
}
function getAbortable () {
let controller
return {
fetch: (url, opts = {}) => {
controller = new AbortController()
return fetch(url, Object.assign({}, opts, {
signal: controller.signal
}))
},
abort: () => controller.abort()
}
}
// Usage
const $input = document.querySelector('input')
const abortable = getAbortable()
$input.addEventListener('input', debounceFetch(handleInput, 250, abortable.abort))
function handleInput ({ target: { value } }) {
abortable.fetch(`/api/search?q=${value}`)
.then(res => res.json())
.then(console.log)
.catch(console.error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment