<form>
<label>Search:</label>
<input type="text" name="state" id="state" />
</form>
<ul id="results"></ul>
body {
min-height: 100vh;
text-align: center;
}
[hidden] {
display: none;
}
* {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue",sans-serif;
font-size: 18px;
font-weight: normal;
}
input {
border-radius: 4px;
padding: 4px;
border: 1px solid gray;
}
button {
padding: .25rem .5rem;
}
div, dialog {
padding: 3rem;
text-align: center;
}
* {
border-radius: 4px;
}
ul {
display: inline-block;
}
form {
display: flex;
justify-content: center;
align-items: center;
gap: .45rem;
padding-top: 1rem;
}
span {
display: inline-block;
background: green;
color: white;
padding: 1rem;
font-size: 5rem;
}
"use strict";
const input = document.getElementById('state');
const resultsList = document.getElementById('results');
function appendResults(results) {
resultsList.innerHTML = '';
results.forEach((r) => {
resultsList.insertAdjacentHTML('beforeend', `<li>${r}</li>`);
});
}
async function search(arg) {
const randoNumber = Math.floor(Math.random() * 10);
return new Array(randoNumber)
.fill(null)
.map((n, index) => `fake result ${index + 1}`);
}
function asyncDebounce(callback) {
let timer = null;
let resolve, reject, promise;
return function (...args) {
reject?.('rejected_pending');
clearTimeout(timer);
({ promise, resolve, reject } = Promise.withResolvers());
timer = setTimeout(() => {
resolve(callback.apply(this, args));
}, 500);
return promise;
};
}
const debouncedSearch = asyncDebounce(search, 500);
input.addEventListener('keyup', async function (e) {
try {
const results = await debouncedSearch(e.target.value);
appendResults(results);
} catch (e) {
// Discard exceptions from intentionally rejected
// promises, but let everything else throw.
if(e !== 'rejected_pending') {
throw e;
}
}
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.