Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sample code for Star Wars API search with delayed timeout.
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>API Search</title>
<input id="search" type="search" />
<div id="results"></div>
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 =;
// Cancel/Clear any existing timers
if (timer !== null) {
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() {
timer = null;
}, DELAY);
function outputNames(names) {
if (names.length > 0) {
resultBox.innerHTML = names.join('<br />');
} else {
resultBox.innerHTML = '';
function getFilteredNames(searchText) {
return fetch('')
.then(function(res) {
return res.json();
.then(function(res) {
return res.results.filter(function(elem, i) {
.map(function(elem) {

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.