Skip to content

Instantly share code, notes, and snippets.

@nitely
Created March 9, 2017 14:48
Show Gist options
  • Save nitely/1e9151e1aeb6cfd2641911152d914e6f to your computer and use it in GitHub Desktop.
Save nitely/1e9151e1aeb6cfd2641911152d914e6f to your computer and use it in GitHub Desktop.
Lame JS puzzle #2 debounce requests
/*
If you were building a search tool and wanted search results to pop up as you
typed but the server call was taxing, write a function that gets called on every
key down but calls the server when the user stops typing for 400ms.
*/
// <input type="text" class="js-search">
// Why a IIFE? coz I don't feel like polluting the global scope with crap [happy face]
(() => {
let search = document.querySelectorAll('input.js-search');
// Why a IIFE? to allow multiple input.search
// and keep a local parent scope (ie to keep
// lastRequest) for each of them
let onKeyStroke = (() => {
let lastRequest = null;
// I see closure! a closure bring the entire outer
// scope wherever it goes, like a hobo
return function _onKeyStroke(ev) {
if (lastRequest != null)
clearTimeout(lastRequest);
lastRequest = setTimeout(() => {
let params = new URLSearchParams(`q=${this.value}`).toString();
fetch(`http://localhost/?${params}`)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}, 400);
}
})();
search.forEach((elem) => elem.addEventListener('input', onKeyStroke));
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment