PUPPETER - Unpredictable pause in loop not functioning as expected

Having an issue with this specific part of the code:

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    // slowMo: 250 // slow down by 250ms
  });
  const page = await browser.newPage();
//some code

// CODE ABOVE WORKS, here is what is not working inside of it:

await page.evaluate(() => {
    function delay(timeout) {
      return new Promise((resolve) => {
        setTimeout(resolve, timeout);
      });
    }
    function randomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    const farms = document.querySelectorAll(".startButton");
    for (let i = 0; i < 3; i++) {
      for (const farm of farms) {
        farm.click();
      }
      delay(randomInteger(820000, 920000));
    }
  });
})();

What I'm trying to achieve is clicking all buttons with a certain class, waiting for some time, and then clicking them again. The delay function seems to be causing issues - it either doesn't work or isn't executed properly. Any help would be appreciated!

#EDIT

The code has been updated as suggested by @Sheun Aluko to include async and await. The issue was related to the website's security system, prompting the need for a workaround involving refreshing the page and changing the loop order. Although it may not be the most efficient solution, it guarantees functionality. Here's an example:

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    // slowMo: 250 // slow down by 250ms
  });

//SOME CODE THAT WORKS
//OUR PART BELOW

  for (let i = 0; i < 150; i++) {
    await page.goto("SOME_URL", {
      waitUntil: "networkidle2",
    });
    await page.evaluate(async (page) => {
      function delay(timeout) {
        return new Promise((resolve) => {
          setTimeout(resolve, timeout);
        });
      }
      function randomInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }

      const farms = document.querySelectorAll('SOME_SELECTOR');

      for (const farm of farms) {
        farm.click();
      }
      await delay(randomInteger(840000, 960000));
    });
  }
})

Answer №1

It appears that the delay function is returning a promise. To ensure the loop pauses between iterations, consider modifying the last line to include

await delay(randomInteger(820000, 920000))
.

Regarding the error you encountered, it could be due to the function being passed to page.evaluate not being marked as async. Although my expertise in Puppeteer is limited, have you tried specifying the provided function as async? For example:

await page.evaluate( async () => { 
   ....
})

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

How come my audio element in HTML refuses to play once I adjust its volume setting?

I'm currently working through a React tutorial and I've encountered an issue with my component. I have implemented an audio HTML tag in the component, with its volume controlled by an input from another React component. However, despite setting u ...

Ways to access the entire parent element, rather than just the individual child element, following the use of e.target

Looking to target the li element itself when clicked, rather than its child elements. The goal is to determine which specific option the user selects from a dropdown menu using event.target in jQuery. If the user chooses an li with a class of 1, set one gl ...

Guide on implementing hover effects in React components

Within my component SecondTest, I have defined an object called useStyle which sets the background color to red. Is it feasible to add a hover effect to this object? const useStyle = { backgroundColor: "red", }; function SecondTest() { return < ...

How come once I close a PrimeNG modal that is defined within a child component, I am unable to reopen it?

Currently, I am developing an Angular application that utilizes PrimeNG. In the process, I encountered a challenge. Initially, I had a component with a PrimeNG Dialog embedded within (refer to this link), and it was functioning properly. To streamline my ...

An item was shown on the HTML page

Having some trouble displaying the graph generated by my R function on the opencpu server. Instead of the desired plot, all I see is [object Object] in the HTML page. Below is the snippet of code from my AngularJS controller: var req = ocpu.rpc("plotGraph ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

jQuery registers the enter event, but does not proceed to trigger the enter action

Hey there, I've been experimenting with jQuery to capture the enter event. Something peculiar is happening though - after pressing enter in the text area, an alert pops up but the text gets entered only after that. Despite trying various solutions, I ...

Exploring the Structure of Trees using JavaScript

Here are my terms: var terms = [ { id: 1, name: "Name 1", parent: null }, { id: 2, name: "Name 2", parent: 6 }, { id: 3, name: "Name 3", parent: null }, { id: 4, name: "Name 4", parent: 2}, { id: 5, name: "Name 5", ...

Creating dynamic elements with FormData

I'm experiencing an issue with sending files via xhr from a dynamically created element. Here's the code snippet in question: $('#thread_file').prepend('<form action="/nti/'+$time+'" enctype="multipart/for ...

How to implement a scrollbar for tables using Angular

How can I implement a vertical scroll bar only for the table body in my Angular code? I want the scroll bar to exclude the header rows. Since all rows are generated by ng-repeat, I am unsure how to add overflow style specifically for the table body. Here ...

Utilize a function from a separate JavaScript file by calling it within the $(document).ready(function()

Refer to this post for more information: Click here I attempted to access a function that was defined in another .js file based on the instructions from the post. However, I encountered an issue. Take a look at my code below: sildemenu.js $(document).re ...

Steps to include a personalized function in a Mongoose Model

One way to extend Mongoose is by adding methods to documents. Here's an example: const userSchema = new mongoose.Schema({ balance: Number }) userSchema.methods.withdrawBalance = function(amount){ const doc = this doc.balance = doc.balance - amou ...

Issues with utilizing Jquery datepicker within a Vue.js component's v-for loop in Laravel

I am facing an issue with the Jquery date picker inside a v-for loop in my vue.js component. The date picker works fine outside of the loop, but inside the loop it does not behave as expected. Here is a snippet of code where the date picker is working cor ...

implement css styling to grid view upon clicking

I have been attempting to add a background color to a grid view row when clicked on that specific row. <script type="text/javascript"> function ChangeRowColor(objref) { objref.style.backgroundcolor = "red"; } </sc ...

Establish initial content for the specified div area

I need help setting page1.html to display by default when the page loads. Can you provide some guidance? Appreciate your assistance in advance. <head>     <title>Test</title>     <meta http-equiv="content-type" content="tex ...

Sign up for our Joomla website by completing the registration form and agreeing to our terms and conditions

I am currently working with Joomla 1.5 and I need to incorporate a checkbox for users to agree to the terms and conditions. I attempted to use the code below, but it is not functioning as expected. Even when the checkbox is ticked, it still triggers an a ...

How to enhance and expand Material-UI components

I am trying to enhance the Tab component using ES6 class in this way: import React from "react"; import {Tab} from "material-ui"; class CustomTab extends Tab { constructor(props){ super(props); } render(){ return super.rende ...

The attempt to perform a Diffie-Hellman key exchange between Python and Node has hit a roadblock, as an error stating that

Currently, I am attempting to establish a DH key exchange between a Python 3.6 client and a Node server deployed in a Docker container with the latest node image (Node version: v13.10.1). On the client side, I am utilizing the cryptography.io library (v2. ...

Struggling with updating scope values when binding data in Angular (particularly with a slider)

Currently, I am utilizing Angular to develop a tool that can take user input from a slider tool and dynamically update an "estimate" field whenever the values are adjusted. However, I'm encountering an issue where the data is only binding in one direc ...

I am trying to access the id of the button that was selected, but I am unsure of how to retrieve the id from it. The method of using

I am trying to retrieve the id of a selected button for deletion purposes. However, I am unable to get the id from it using 'this.id'. Is there another method I should be using? Below is the code where I create the button: var deleteEmployer= d ...