1

I'm writing a Chrome extension that scrolls & listens for newly added child nodes to a parent node.

It then waits a random amount of time, then scrolls down again if more children are added, and stops if in the next 5 seconds nothing appears via ajax (when the list of results has been exhausted, for example).

My question is how I should handle waiting variable amounts of time between each event scroll reaction.

I'd like for it to work politely (yet not fail to scroll down if all 50 elements are loaded at once and the scrolls generated aren't quite enough to get to the next ajax load point).

Any ideas or ways I should think about this? (This is for a totally benign use case btw)

lollercoaster
  • 15,969
  • 35
  • 115
  • 173

1 Answers1

0

A good solution is a little tricky, but totally works:

var canPoll = true;  
var timeout = ... whatever ...; // if we want an absolute timeout
var startTime = (new Date()).getTime();

function randomWait(t) {
   // ... waits a random period of time
}

function isDone() {
   // ... check if done. returns boolean
}

function complete() {
   // ... run when everything is done
}

(function recursive() {
    // check for our absolute walltime timeout
    canPoll = ((new Date).getTime() - startTime) <= timeout;

    // check other conditions too
    if (!fn() && canPoll)  {
        // repeat!
        setTimeout(recursive, randomWait(interval));
    } else {
        // we're done
        complete();
    }
})();

Adapted from this wonderful answer.

lollercoaster
  • 15,969
  • 35
  • 115
  • 173