skip to Main Content

I want the script call to wait for 2 seconds after every 5 pages.

My requirements are that the for loop should wait for 2 seconds when pageData.Number reaches page 5. So basically, the loop should wait for 2 seconds after every 5 pages.

Not sure how to check if the page reaches page 5 and wait for 2 seconds.

for (var i = 1; i <= pageData.Number; i++) {
  var pageRequest = $.getJSON(URL, function (data) {
    if (i % 5 == 0) {
      sleep(5000);
    }
    /* .... */
  }).fail(function () {
    errorPage.push(i);
  });
}

// from https://www.sitepoint.com/delay-sleep-pause-wait/
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

2

Answers


  1. I think you need something like this. It uses javascript remainder operator and a custom sleep function.

    for (var i = 1; i <= pageData.Number; i++) {
      //setTimeout(func, 2000);              
      var pageURL = Url + "?startDate=" + moment(startDate).format(dateFormat) + "&endDate=" + moment(endDate).add(1, 'day').format(dateFormat) + "&pageNumber=" + i;               
      var pageRequest = $.getJSON(URL, function (data) {
      if (i % 5 == 0) {
        sleep(2000);
      }
    }
    
    // from https://www.sitepoint.com/delay-sleep-pause-wait/
    function sleep(milliseconds) {
      const date = Date.now();
      let currentDate = null;
      do {
        currentDate = Date.now();
      } while (currentDate - date < milliseconds);
    }
    Login or Signup to reply.
  2. Here’s how you could do it – with async/await and without jQuery.

    /**
     * @summary waits a specified number of seconds
     * @param {number} [seconds] seconds to wait
     * @returns {Promise<void>}
     * @link https://github.com/samliew/se-electionbot/blob/master/src/bot/utils.js#L910
     */
    const wait = (seconds = 1) => new Promise((r) => setTimeout(r, seconds * 1e3));
    
    /**
     * Your main function, async
     */
    (async function () {
      
      // Variables, from your question
      const errorPage = [];
      const pageData = {
        Number: 10,
      };
    
      // test json endpoint, you can substitute this with an array
      const url = 'https://reqbin.com/echo/get/json';
      
      for (let i = 1; i <= pageData.Number; i++) {
      
        // Fetch url
        const data = await fetch(url).then(response =>
          // Convert data to json, or return null on error
          response.ok ? response.json() : errorPage.push(i) && null
        );
        
        // Data exists
        if(data) {
            // Do something with data
            console.log(`Request ${i} completed.`);
        }
    
        // Short wait after every fifth request
        if (i % 5 === 0) {
          console.log('Waiting for 2 seconds...');
          await wait(2);
        }
      }
    
      console.log('Done!');
    
    })(); // end main function
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search