Created
September 2, 2024 12:47
-
-
Save imbharat420/7e8713a5a407cbcd81b5cc8cd20b475b to your computer and use it in GitHub Desktop.
AbortController Debounce.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function debounce(fn,delay){ | |
let timeoutid =0; | |
let abortController = new AbortController() | |
return function(...args){ | |
if(timeoutid){ | |
clearTimeout(timeoutid) | |
abortController.abort(); | |
} | |
abortController = new AbortController() | |
signal = abortController.signal | |
timeoutid = setTimeout(()=>{ | |
fn(...args,signal) | |
},delay) | |
} | |
} | |
function fn(query,signal){ | |
fetch('https://jsonplaceholder.typicode.com/todos/1',{signal}) | |
.then((res)=>res.json()) | |
.then((data)=>{ | |
if(!signal.aborted){ | |
console.log(data) | |
} | |
}).catch(err=>console.log(err)) | |
} | |
const dFxn = debounce(fn,100) | |
dFxn("hello") | |
dFxn("hello") | |
dFxn("hello") | |
dFxn("hello") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment