Skip to content

Instantly share code, notes, and snippets.

@lalosh
Created August 11, 2021 12:30
Show Gist options
  • Save lalosh/0bf01d3e321af32e6acb70220b4e1a12 to your computer and use it in GitHub Desktop.
Save lalosh/0bf01d3e321af32e6acb70220b4e1a12 to your computer and use it in GitHub Desktop.
Lodash debounce with cancellation
// Copyright 2021 Lableb
/**
* Lodash debounce with cancellation capabilities
*
* @author Louay Al-osh
*/
const lodash = require("lodash");
/**
* Search Bar is a good example of where to make a debounced requests
*/
let searchRef;
/**
* the function you want to debounce(most likely doing an API request)
*/
function SearchAtLableb() {
console.log('Search done');
}
function debouncedSearch() {
// cancel any old refs
if (searchRef && searchRef.cancel)
searchRef.cancel();
// create new instance and save for later
searchRef = lodash.debounce(SearchAtLableb, 1000);
// execute will start after 1000 unless cancelled because the function is re-invoked again
searchRef();
}
/**
* because it's debounced with a cancellation capability
* no matter how many times you debounce it, it will be called only once
* (the last call only)
*/
debouncedSearch();
debouncedSearch();
debouncedSearch();
debouncedSearch();
debouncedSearch();
debouncedSearch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment