On my website, I have implemented an Intersection Observer that monitors a specific element in the viewport. The observer triggers a series of classList.add() and classList.remove() methods, applying different animate.css animation classes. Everything works as expected with the Intersection Observer, but I am facing issues with the async/await keywords. The timers for the animations start immediately once the Observer is activated, making it difficult to stop the animation sequence when needed.
To work around this issue, I have adjusted the setTimeout() delays to ensure that the animations play in the correct order. However, this approach does not solve the problem of halting the animation sequence.
I have gone through various resources, including MDN documentation, but I am unable to determine if my usage of async/await is incorrect or if it is simply not compatible with an Intersection Observer.
Below is the code snippet for my Intersection Observer and its related functions:
const contactSectionSubmitButtonWrapper = document.querySelector('.submit-button-wrapper');
async function timer(fn, milliseconds){
await setTimeout(fn, milliseconds);
}
async function animation01(){
if(document.activeElement.id == "name-field" || document.activeElement.id == "email-field" || document.activeElement.id == "message-field") {
console.log('Submit button animation stopped because an input field is active.');
} else {
console.log('Submit button animation 01');
contactSectionSubmitButtonWrapper.classList.add('animate__pulse');
}
}
// The code for animation02 to animation13 is omitted for brevity.
const contactSectionSubmitButtonObserver = new IntersectionObserver(
async(entries)=>{
console.log(entries);
for (const entry of entries) {
if(entry.isIntersecting) {
await timer(animation01, 3000);
await timer(animation02, 6000);
await timer(animation03, 9000);
await timer(animation04, 12000);
await timer(animation05, 15000);
await timer(animation06, 18000);
await timer(animation07, 21000);
await timer(animation08, 24000);
await timer(animation09, 27000);
await timer(animation10, 30000);
await timer(animation11, 31000);
await timer(animation12, 35000);
await timer(animation13, 38000);
}
}
},
{
threshold: 0.1,
root: null,
rootMargin: '0px'
}
);
contactSectionSubmitButtonObserver.observe(contactSectionSubmitButtonWrapper);