0

I am making a chrome extension for web automation.The first step is to get a list of sites and instructions from a server in a delimiter-format. Once the list is obtained it is divided into an array that i call "siteArray".

The site array is then divide into another array i call "instructionsArray" and among those items in the array one of them is the duration spent on the site i.e instructionsArray[5] has the value of "10" seconds. {the duration is not the same for all the sites}

My question arises in how to delay(implementing duration)

One implementation I found is using a sleep function which turns out to be inefficient as it is just a long for loop

see code:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

and then:

getlist();

for each(siteArray){
instructionsArray = siteArray[count].split(delimiter);
gotoUrl(instructionsArray[1]);
sleep(instructionsArray[5]);
count++;
}

Where

  1. getlist() fetches a list of instructions and splits into the siteArray .
  2. gotoUrl() changes url.
  3. sleep() runs the sleep function.

Is there a better way to implement a duration/wait/delay.

Bob Kimani
  • 1,114
  • 1
  • 20
  • 38
  • Possible duplicate of [Sleep/Pause/Wait in Javascript](http://stackoverflow.com/questions/7854820/sleep-pause-wait-in-javascript) – wOxxOm Aug 17 '16 at 17:27
  • @wOxxOm using setTimeout for me didn't work.since the setting timeout in loop will add url1 and url2 to be visited at the same time – Bob Kimani Aug 17 '16 at 18:33

2 Answers2

0

Rework the way you iterate over the array: process one entry, set a timer, repeat.

var count = 0;
processSite();

function processSite() {
    if (count >= siteArray.length) {
        console.log('all done!');
        return;
    }
    var instructionsArray = siteArray[count].split(delimiter);
    count++;
    gotoUrl(instructionsArray[1]);
    setTimeout(processSite, instructionsArray[5]);
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
0

After giving much thought into it I have solved the issue. Using wOxxOm's idea I came up with this 'sub-idea' to create multiple timeouts i.e

for(index = 1;index<(siteArray.length);index++){
            instructionsArray = siteArray[index].split(delimiter);
            bigtime+=instructionsArray[5];
            setTimeout(function(){processNext(count)},bigtime);

        }

This code creates multiple timeout functions for each site. similar to :

setTimeout(function(){processNext(count)},10 sec);
setTimeout(function(){processNext(count)},10+10 sec);
setTimeout(function(){processNext(count)},10+10+10 sec);

but in a dynamic way.

The count variable is change in the processNext function:

processNext(count){
instructionsArray = siteArray[count].split(delimiter);
visitUrl(instructionsArray[1]);
count++;
}

I give Thanks to wOxxOm for the insight.

Bob Kimani
  • 1,114
  • 1
  • 20
  • 38