- Published
From Callback to Async/Await: Sequential Fade-In Animation

目錄
Note: This post is translated by AI. If you find any unnatural phrasing or errors, please feel free to contact me via email or other channels. Your feedback is appreciated!
Foreword
The article is aimed at those know the concept of Callback Hell, Promise and Async/Await, but haven't dealt with it or not completely understand the difference.
I will guide you the three ways to implement "Sequential Fade In elements after clicking a button".

Intuitive solution:
- For fade in, add
transitionto elements, and change theopacitywhile clicking the button. - Sequential Fade In? The latter element's fading in has to "wait" for the fore elements fading in.
- If you want to "wait" in JavaScript, the first thing comes to my mind is
setTimeout. Waiting one by one is about calling asetTimeoutafter asetTimeoutcountdown.
So, the code is like this:
const startBtn = document.getElementById('startBtn');
const container = document.getElementById('container');
const first = document.getElementById('first');
const second = document.getElementById('second');
const third = document.getElementById('third');
const forth = document.getElementById('forth');
const fifth = document.getElementById('fifth');
const resetBtn = document.getElementById('reset');
startBtn.addEventListener('click', function () {
this.style.display = 'none';
container.classList.remove('hidden');
setTimeout(() => {
first.classList.remove('hidden');
setTimeout(() => {
second.classList.remove('hidden');
setTimeout(() => {
third.classList.remove('hidden');
setTimeout(() => {
forth.classList.remove('hidden');
setTimeout(() => {
fifth.classList.remove('hidden');
setTimeout(() => {
resetBtn.classList.remove('hidden');
}, 500);
}, 500);
}, 500);
}, 500);
}, 500);
}, 500);
});
That's it! Each Element can fade in each 0.5 seconds after clicking the startBtn. Is it the end? Uh...there's something weird...Is it the notorious Callback Hell?