The issue with async/await functionality in Intersection Observer

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);

Answer №1

One flaw in the code is that setTimeout is not an asynchronous function, so it cannot be awaited.

To address this issue, we can modify the timer function as shown below:

async function timer(fn, milliseconds){
   return new Promise(resolve => {
      setTimeout(()=> {
        resolve(fn())
      }, milliseconds)
    });
}

An illustration of the intended goal:

async function timer(fn, milliseconds){
   return new Promise(resolve => {
      setTimeout(()=> {
        resolve(fn())
      }, milliseconds)
    });
}

const entries = [1,2,3,4,5,6]
const driver = async ()=>{
  for (const entry of entries) {
    await timer(()=> console.log(entry), 1000);
  }
}

driver();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing a character's appearance with custom CSS styling

In my code, I want to highlight a single character throughout the page. I want the lines between each word to be a different color from the rest of the text using CSS, without having to add span tags to each one individually. Anti-virus End Point | Dis ...

Issue with Wordpress css rendering on Internet Explorer

My webpage is functioning well in Chrome and Firefox, but I'm facing compatibility issues with Internet Explorer. I've identified several bugs related to tables and layout, however, I'm struggling to resolve the font and text-transform prob ...

What is the most effective way to receive all values sent to an Observer upon a new subscription?

I have an observer that receives various values emitted to it at different times. For instance sub = new Subject<any>(); sub.next(1); sub.next(2); sub.next(3); #hack 1 sub.next(4); sub.next(5); sub.next(6); #hack 2 If there is a ...

When a user clicks on a child element in ReactJS, the onclick event returns as undefined

I am experiencing an issue with my restaurants list component. While I have an onClick event set up for each list item, clicking on a child element of the list item does not trigger the expected response. When this occurs, nothing happens or I see an undef ...

Combine the text value from a textbox and the value from a checkbox into a single

I'm trying to solve a challenge regarding appending values from text fields (excluding empty ones) and checkboxes in a specific order to form a string. It should be in the format: name|T|F_name|F|F. Once I've created this string, I plan to send i ...

What could be causing the service method in the controller not to be called by Node JS?

In my current Node JS project, the folder structure of my app is as follows: src │ index.js # Main entry point for application └───config # Contains application environment variables and secrets └───controllers # Hou ...

Frequently encountering broken styles in Magento 1.9 due to missing CSS and JS files

Recently, I've been facing frequent style breaking issues on my Magento sites (1.9.2+). This results in the home page displaying only text with missing CSS, JS, and images. To fix this problem, I usually clear the cache by deleting the var/cache fold ...

The function req.checkBody does not exist

Currently, I am following the guidance of the Mozilla Express tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms). However, as I reached the section involving express-validator, I encountered a persistent error messag ...

What are the risks associated with allowing user-generated HTML or Javascript code on a website?

Is it really dangerous to allow users to edit HTML with Jinja2 templates and access some server-side variables that will be rendered later? I know Google uses Caja Compiler to sanitize and sandbox HTML served from Google Apps Script. Should I be concerned ...

What is the best method to access an element with Vue.js?

I currently have a form set up like this <form v-on:submit.prevent="save_data(this)"></form> and a method defined in Vue.js like this methods: { save_data: function(f){ } } In jQuery, we can access the form using $(f)[0] My question ...

In Pure JavaScript, an HTML element is added every time the click event is triggered

Hey everyone, I'm facing a small issue and I could use some help fixing it. I need to implement an onclick event that adds HTML code every time it's clicked. I am hesitant to use innerHTML due to its potential risks. Here is the code snippet: bu ...

Could a potential concurrency issue arise when handling a Queue in JavaScript?

I am faced with a situation where I need to persist an array of properties via AJAX calls to a database. However, the current API does not allow sending the strings in batches, and simple looping will cause overwriting issues. To overcome this, I have impl ...

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

Unable to display content when the button is triggered

I am facing an issue with hiding a div (class="login-form") and displaying it only after clicking the Login button on my HTML page using jQuery. However, despite clicking the button, the login form does not appear. Can anyone help me understand why this ha ...

The dropdown menu is currently activated, but not the individual items within it

Is there a way to make the dropdown menu active when I click on an item, specifically making the word Services active? How can this be achieved? <nav class="navbar navbar-light navbar-expand-xl"> <a class="navbar-brand" hre ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

The variable in the HTML input value is not fully visible when filling out the HTML form

I am working with a Python Flask code where I have passed a dictionary to an HTML form. The table in the form correctly displays both keys and values, but when trying to populate a form field with the value from the dictionary, only the first word is displ ...

How to create HTML buttons with CSS that maintain proper proportions?

How can I ensure that my HTML buttons adjust proportionally to different screen sizes? I've been working on coding an Android app using HTML and CSS, and everything seems to be running smoothly. However, when I share the file with a friend, he compla ...

AngularJS integration with Bootstrap Confirmation jQuery plugin

I am currently struggling to implement the Bootstrap-Confirmation plugin with AngularJS. Despite following instructions from this YouTube tutorial, I cannot seem to get the directive to function correctly. A related query on Stack Overflow references a di ...

Challenge with modal dialog scrolling on iPad and iPhone

Our website contains various pages that open JQuery 'Modal Dialog' boxes. These modal dialog boxes function well in all web browsers. However, there is an issue when viewing the website on an iPad or iPhone, which seems to be a common problem. ...