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

React Component State in JavaScript is a crucial aspect of building

What happens when the expression [...Array(totalStars)] is used within a React Component? Is the result an array with a length of 5, and what are the specific elements in this array? We appreciate your response. class StarRating extends Component { ...

Tips for incorporating a value within the AngularJS select function

Having an issue with passing a list value in the html select method using AngularJS. Here is my code: app.js $scope.subcategory = function() { var query = "SELECT unit FROM Length;"; $cordovaSQLite.execute(db, query).then(function(res) { ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

When the input field is clicked, the file:/// URL is sent

Currently, my HTML page contains a form that includes an input field for URLs. Ideally, upon typing in the URL and clicking the button, I intend to be redirected to that website. However, the issue lies in the fact that instead of redirecting me to the p ...

How can one gain access to a specifically generated element?

In my task of dynamically generating multiple elements, I am facing an issue related to accessing specific ones. To illustrate this problem as simply as possible, I have provided the following code: $(document).ready(function() { var num1 = 0; v ...

Guide to creating individual column templates in Kendo-UI grid

I recently started using Kendo-UI in my project and wanted to have a column in my grid display an image button along with a field, similar to the 'Contact Name' column in the documentation here. After exploring the documentation, I came across th ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

What is the best way to include temporary attributes on a mongoose object solely for the purpose of a response, without saving them to the database

I am looking to add extra temporary properties with additional data to the response but have encountered some difficulties. 'use strict'; var mongoose = require('mongoose'); var express = require('express'); var app = expres ...

Tips for successfully transferring data using a dynamic key in a Semantic UI Vue dropdown

My current challenge involves troubleshooting the semantic-ui-vue dropdown functionality. To view the issue, visit my sandbox link: https://codesandbox.io/s/3qknm52pm5. Within the sandbox environment, there are two dropdown menus labeled as From and To. ...

Javascript code generated by PHP is failing to run

When you select an option from the dropdown below: <select id='dropdown' name='dropdown' onchange='showChart(this.value)'> <option value="1">Foo</value> <option value="2">Bar</value> </select& ...

Using Vue to input an array

I'm struggling with how to handle this issue. The task involves taking input which should be a URL, and the user should be able to enter multiple URLs. For instance: <input type="text" v-model="fields.urls" class=&quo ...

NodeJS: Implement a method to delete a file or folder using a path without the file extension (Strategic approach)

I am facing a challenge in deleting a file or folder based on a path that does not include an extension. Consider the path below: /home/tom/windows The name windows could refer to either a folder named windows OR a file named windows.txt Given that the ...

Unable to smoothly expand Div in React using Tailwind

I'm facing a challenge in animating a div that contains input elements. I want it to expand smoothly - initially, the text area is small and the other two inputs and buttons are hidden. When clicking on the text area, the input and button should be re ...

OroCrm is ensuring that Symfony2 profiler seamlessly updates the footer data without triggering a 404 error page within a popup

As a newcomer to OroCrm, I recently installed and configured it on my DEV environment using the app_dev.php entry point. After setting up OroCrm, I immediately noticed the Symfony2 profiler bar appearing at the bottom of the interface. While this was a he ...

When I try to access localhost, it directs me to http://localhost:3000/myprofile%20 instead of localhost:/3000/myprofile

Every time I try to log into my profile page with the correct login credentials, I get redirected to http://localhost:3000/myprofile%20, but then receive a 404 error. This is what my code looks like: // Login Route router.post('/login', functi ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

Generate - Create 2 different versions of the web application

Currently, I am in the process of learning Grunt and exploring ways to generate 2 variations of an application with different configuration settings. My goal is to have one version where a boolean in a specific .js file is set to false, and another versio ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

Javascript code fails to execute properly on IE8

I have a scenario where I am working with two drop-down menus. When the user selects an option from one menu, it should dynamically change the options in the other menu. However, I'm facing an issue with Internet Explorer where the second drop-down me ...

What is the default method for automatically disabling drop down fields?

I've created a script that will gray out a drop-down field if a prior selection wasn't made. Once the appropriate choice is selected, the grayed-out field will become active. My query is, how can I set the drop-down field to be initially grayed ...