Home Programming News JavaScript waitFor Polling

JavaScript waitFor Polling

JavaScript waitFor Polling

As extra of the JavaScript builders write turns into asynchronous, it is solely pure to wish to attend for situations to be met. That is very true in a world with asynchronous testing of situations which do not present an express await. I’ve written about waitForever, waitForTime, and JavaScript Polling prior to now, however I wished to have a extra fashionable method of awaiting a given state. Let’s take a look at this tremendous helpful waitFor operate!

waitFor is an async operate that permits builders to offer a situation operate, polling interval (in milliseconds), and non-obligatory timeout (in milliseconds).

// Polls each 50 milliseconds for a given situation
const waitFor = async (situation, pollInterval = 50, timeoutAfter) => {
  // Observe the beginning time for timeout functions
  const startTime = Date.now();

  whereas (true) {
    // Verify for timeout, bail if an excessive amount of time handed
    if(typeof(timeoutAfter) === 'quantity' && Date.now() > startTime + timeoutAfter) {
      throw 'Situation not met earlier than timeout';

    // Verify for conditon instantly
    const end result = await situation();

    // If the situation is met...
    if(end result) {
      // Return the end result....
      return end result;

    // In any other case wait and test after pollInterval
    await new Promise(r => setTimeout(r, pollInterval));

Utilizing this operate is so simple as simply offering a situation operate:

await waitFor(() => doc.physique.classList.has('loaded'));

Timing out the interval and timeout can be easy:

await waitFor(
  () => doc.physique.classList.has('loaded'),
  // Checks each 100 milliseconds
  // Throws if the "loaded" class is not on the physique after 1 second

In a perfect world, builders would at all times have a deal with on the Promise that may very well be await‘d or then‘d. In follow, nevertheless, that is not at all times the case, particularly in a testing surroundings. Having the ability to await a situation in any surroundings is an absolute should, so maintain this snippet in your toolbox!



Please enter your comment!
Please enter your name here