Skip to content

Instantly share code, notes, and snippets.

@harunorimurata
Last active March 26, 2020 07:18
Show Gist options
  • Save harunorimurata/01e0ad3fc504a462a4ce2535ec76235b to your computer and use it in GitHub Desktop.
Save harunorimurata/01e0ad3fc504a462a4ce2535ec76235b to your computer and use it in GitHub Desktop.
function debounce(fun, wait = 0) {
let id = null;
return () => {
if (id !== null) clearTimeout(id)
id = setTimeout(() => {
fun();
id = null;
}, wait);
};
}
const debounce = (fun: () => any, wait = 0): () => void => {
let id: NodeJS.Timer|null = null;
return () => {
if (id !== null) clearTimeout(id)
id = setTimeout((): void => {
fun()
id = null
}, wait)
}
}
function debounce(fun, wait = 0) {
let id = null;
return (x) => {
return new Promise(resolve => {
if (id !== null) clearTimeout(id);
id = setTimeout(() => {
id = null;
resolve(fun(x));
}, wait);
});
}
}
// var hoge = debounce(x=>x + 1, 1000)
// hoge(1).then(x => console.log(x));
// hoge(3).then(x => console.log(x));
// hoge(2).then(x => console.log(x));
// hoge(5).then(x => console.log(x));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment