Skip to content

Instantly share code, notes, and snippets.

@KyleMit
Last active June 9, 2021 03:38
Show Gist options
  • Save KyleMit/dd1b1aca704c4f502b0702bb88548ae3 to your computer and use it in GitHub Desktop.
Save KyleMit/dd1b1aca704c4f502b0702bb88548ae3 to your computer and use it in GitHub Desktop.
Loading Spinner Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Loading Spinner Example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<main>
<h1>Loading Spinner Sample</h1>
<p>
<a href="https://gist.github.com/KyleMit/dd1b1aca704c4f502b0702bb88548ae3/">Source on gist</a>
</p>
<p>
<button id="btnAsync">Wait Async</button>
<button id="btnSync">Wait Sync</button>
</p>
</main>
<div id="loading">
Loading...
</div>
<script src="./script.js"></script>
</body>
</html>
document.getElementById("btnAsync").addEventListener("click", handleClickAsync)
document.getElementById("btnSync").addEventListener("click", handleClickSync)
async function handleClickAsync() {
console.time("math")
console.log("add spinner")
addSpinner()
await waitAsync(2000)
removeSpinner()
console.log("remove spinner")
console.timeEnd("math")
}
async function handleClickSync() {
console.time("math")
console.log("add spinner")
addSpinner()
waitSync(2000)
removeSpinner()
console.log("remove spinner")
console.timeEnd("math")
}
async function waitAsync(ms) {
await new Promise(r => setTimeout(r, ms));
}
function waitSync(ms) {
let start = Date.now()
let stop = start + ms
let current
do {
current = Date.now()
} while (current < stop)
}
function addSpinner() {
document.body.classList.add("isLoading")
}
function removeSpinner() {
document.body.classList.remove("isLoading")
}
#loading {
background: #2d2d2d45;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 9999;
align-items: center;
justify-content: center;
text-align: center;
}
#loading {
display: none;
}
.isLoading #loading {
display: flex;
}
/* Demo styles */
main {
text-align: center;
}
main>button {
margin: 8px;
padding: 4px 12px;
font-size: 1.2rem;
border-radius: 4px;
border: 1px solid grey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment