Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample code for Star Wars API search with delayed timeout.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>API Search</title>
</head>
<body>
<input id="search" type="search" />
<div id="results"></div>
</body>
</html>
const search = document.querySelector('#search');
const resultBox = document.querySelector('#results');
// Add delay to prevent making API calls
// on every input. Bad for performance
// and can cause lag in the UI
const DELAY = 500;
let timer = null;
search.addEventListener('input', function(e) {
const searchText = e.target.value.toLowerCase();
// Cancel/Clear any existing timers
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
// Set the delayed timeout. Should the user
// not interact with the search text field
// within the DELAY period then the API call
// will be triggered
timer = setTimeout(function() {
getFilteredNames(searchText).then(outputNames);
timer = null;
}, DELAY);
});
function outputNames(names) {
console.log(names);
if (names.length > 0) {
resultBox.innerHTML = names.join('<br />');
} else {
resultBox.innerHTML = '';
}
}
function getFilteredNames(searchText) {
return fetch('https://swapi.co/api/people')
.then(function(res) {
return res.json();
})
.then(function(res) {
return res.results.filter(function(elem, i) {
return elem.name.toLowerCase().includes(searchText);
})
.map(function(elem) {
return elem.name;
});
});
}
@graphicbeacon

This comment has been minimized.

Copy link
Owner Author

graphicbeacon commented May 4, 2019

You can paste this in an online editor like JSBIN or JSFiddle to test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.