Skip to content

Instantly share code, notes, and snippets.

@greathmaster
Forked from alexnoz/debounce-abort-fetch.js
Created March 24, 2021 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greathmaster/908029974c77ead292468ef42f165338 to your computer and use it in GitHub Desktop.
Save greathmaster/908029974c77ead292468ef42f165338 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