Wait for an element to reach the given readyState by polling. The HTML5 video element exposes a `readystatechange` event that could be listened for instead, but it seems to be unreliable on some browsers.
557391
function waitForReadyState(element, readyState, interval, done) {
  var timer = setInterval(function() {
    if (element.readyState >= readyState) {
      clearInterval(timer);
      done(null, true);
    }
  }, interval);
}
235447
def waitForInitialState( self ):
        ''''''
        # wait for a valid observation
        world_state = self.agent_host.peekWorldState()
        while world_state.is_mission_running and all(e.text=='{}' for e in world_state.observations):
            world_state = self.agent_host.peekWorldState()
        # wait for a frame to arrive after that
        num_frames_seen = world_state.number_of_video_frames_since_last_state
        while world_state.is_mission_running and world_state.number_of_video_frames_since_last_state == num_frames_seen:
            world_state = self.agent_host.peekWorldState()
        world_state = self.agent_host.getWorldState()

        if world_state.is_mission_running:
                
            assert len(world_state.video_frames) > 0, 'No video frames!?'
            
            obs = json.loads( world_state.observations[-1].text )
            self.prev_x   = obs[u'XPos']
            self.prev_y   = obs[u'YPos']
            self.prev_z   = obs[u'ZPos']
            self.prev_yaw = obs[u'Yaw']
            print('Initial position:',self.prev_x,',',self.prev_y,',',self.prev_z,'yaw',self.prev_yaw)
            
            if save_images:
                # save the frame, for debugging
                frame = world_state.video_frames[-1]
                image = Image.frombytes('RGB', (frame.width, frame.height), bytes(frame.pixels) )
                self.iFrame = 0
                self.rep = self.rep + 1
                image.save( 'rep_' + str(self.rep).zfill(3) + '_saved_frame_' + str(self.iFrame).zfill(4) + '.png' )
            
        return world_state
706968
public ReadyState getReadyState() {
        if (stream == null) {
            return EventSource.ReadyState.CONNECTING;
        }
        else {
            switch (stream.getReadyState()) {
            case CONNECTING:
                return EventSource.ReadyState.CONNECTING;
                
            case OPEN:
                return EventSource.ReadyState.OPEN;

            case CLOSING:
            case CLOSED:
            default:
                return EventSource.ReadyState.CLOSED;
            }
        }        
    }
842251
def wait_for_element(self, selector, by=By.CSS_SELECTOR,
                         timeout=settings.LARGE_TIMEOUT):
        
        if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
            timeout = self.__get_new_timeout(timeout)
        return self.wait_for_element_visible(selector, by=by, timeout=timeout)
389052
def pause_and_wait_for_user(self, timeout=None, prompt_text='Click to resume (WebDriver is paused)'):
        
        timeout = timeout if timeout is not None else self.user_wait_timeout
        # Set the browser state paused
        self.paused = True

        def check_user_ready(driver):
            """Polls for the user to be "ready" (meaning they checked the checkbox) and the driver to be unpaused.
            If the checkbox is not displayed (e.g. user navigates the page), it will re-insert it into the page

            @type driver: WebDriverWrapper
            @param driver: Driver to execute
            @return: True if user is ready, false if not
            """
            if driver.paused:
                if driver.is_user_ready():
                    # User indicated they are ready; free the browser lock
                    driver.paused = False
                    return True
                else:
                    if not driver.is_present(Locator('css', '#webdriver-resume-radio', 'radio to unpause webdriver')):
                        # Display the prompt
                        pause_html = staticreader.read_html_file('webdriverpaused.html')\
                            .replace('\n', '')\
                            .replace('PROMPT_TEXT', prompt_text)
                        webdriver_style = staticreader.read_css_file('webdriverstyle.css').replace('\n', '')


                        # Insert the webdriver style
                        driver.js_executor.execute_template_and_return_result(
                            'injectCssTemplate.js',
                            {'css': webdriver_style})

                        # Insert the paused html
                        driver.js_executor.execute_template_and_return_result(
                            'injectHtmlTemplate.js',
                            {'selector': 'body', 'html': pause_html})
            return False

        self.wait_until(
            lambda: check_user_ready(self),
            timeout=timeout,
            failure_message='Webdriver actions were paused but did not receive the command to continue. '
                            'You must click the on-screen message to resume.'
        )

        # Remove all injected elements
        self.js_executor.execute_template_and_return_result(
            'deleteElementsTemplate.js',
            {'selector': '.webdriver-injected'}
        )
114778
def element_call(precondition = nil, &block)
      caller = caller_locations(1, 1)[0].label
      already_locked = Wait.timer.locked?
      Wait.timer = Wait::Timer.new(timeout: Watir.default_timeout) unless already_locked

      begin
        check_condition(precondition, caller)
        Watir.logger.debug "-> `Executing #{inspect}##{caller}`"
        yield
      rescue unknown_exception => ex
        element_call(:wait_for_exists, &block) if precondition.nil?
        msg = ex.message
        msg += '; Maybe look in an iframe?' if @query_scope.iframe.exists?
        custom_attributes = @locator.nil? ? [] : selector_builder.custom_attributes
        unless custom_attributes.empty?
          msg += "; Watir treated #{custom_attributes} as a non-HTML compliant attribute, ensure that was intended"
        end
        raise unknown_exception, msg
      rescue Selenium::WebDriver::Error::StaleElementReferenceError
        reset!
        retry
      rescue Selenium::WebDriver::Error::ElementNotVisibleError, Selenium::WebDriver::Error::ElementNotInteractableError
        raise_present unless Wait.timer.remaining_time.positive?
        raise_present unless %i[wait_for_present wait_for_enabled wait_for_writable].include?(precondition)
        retry
      rescue Selenium::WebDriver::Error::InvalidElementStateError
        raise_disabled unless Wait.timer.remaining_time.positive?
        raise_disabled unless %i[wait_for_present wait_for_enabled wait_for_writable].include?(precondition)
        retry
      rescue Selenium::WebDriver::Error::NoSuchWindowError
        raise NoMatchingWindowFoundException, 'browser window was closed'
      ensure
        Watir.logger.debug "<- `Completed #{inspect}##{caller}`"
        Wait.timer.reset! unless already_locked
      end
    end
1188205
def wait_until_visible(self, timeout=None):
        
        try:
            self.utils.wait_until_element_visible(self, timeout)
        except TimeoutException as exception:
            parent_msg = " and parent locator '{}'".format(self.parent) if self.parent else ''
            msg = "Page element of type '%s' with locator %s%s not found or is not visible after %s seconds"
            timeout = timeout if timeout else self.utils.get_explicitly_wait()
            self.logger.error(msg, type(self).__name__, self.locator, parent_msg, timeout)
            exception.msg += "\n  {}".format(msg % (type(self).__name__, self.locator, parent_msg, timeout))
            raise exception
        return self
925927
function waitelem (self, selector, done) {
  let elementPresent
  eval('elementPresent = function() {' + // eslint-disable-line
    `  var element = document.querySelector('${selector}');` +
    '  if (!element) { return null }' +
    '  for (let key in element) {' +
    '    if (key.startsWith(\'__reactInternalInstance$\')) {' +
    '      const compInternals = element[key]._currentElement;' +
    '      const compWrapper = compInternals._owner;' +
    '      const {props, state, context} = compWrapper._instance;' +
    '      return {props, state, context}' +
    '    }' +
    '  }' +
    '  return null;' +
    '}')
  waitfn.apply(this, [self, elementPresent, done])
}
654141
function(state) {
    if (state == self.LOADING || self.readyState !== state) {
      self.readyState = state;

      if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
        self.dispatchEvent("readystatechange");
      }

      if (self.readyState === self.DONE && !errorFlag) {
        self.dispatchEvent("load");
        // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
        self.dispatchEvent("loadend");
      }
    }
  }
6452
function _waitForElement(browser, selector, asserter, timeout, pollFreq) {
  /* eslint no-use-before-define:0 */
  timeout = timeout || 2000;
  pollFreq = pollFreq || 50;

  const endTime = Date.now() + timeout;

  function attempt() {
    const element = browser.elementByCssSelectorOrNull(selector);
    return element
      .then(asserter.assert)
      .catch(retry)
      .then(_.constant(element));
  }

  function retry(error) {
    if (!error.retriable) {
      throw error;
    }
    if (Date.now() >= endTime) {
      error.message = `Timeout (${timeout}ms): ${error.message}`;
      throw error;
    }
    return new Promise(resolve => setTimeout(resolve, pollFreq)).then(attempt);
  }

  return attempt();
}
646445
public static void waitWhileState(final DeviceProxy proxy, final DevState waitState, final long timeout)
	    throws DevFailed, TimeoutException {
	waitWhileState(proxy, waitState, timeout, 300);
    }
1310960
function onReadystatechange(e) {

	if (!(e instanceof Event)) {
		throw new TypeError('Invalid event was given');
	}

	if (document.readyState == 'interactive') {
		makeReady.call(this);
	}

	if (document.readyState == 'complete') {
		makeLoaded.call(this);
	}
}
783761
public static void waitForState(final DeviceProxy proxy, final DevState waitState, final long timeout)
	    throws DevFailed, TimeoutException {
	waitForState(proxy, waitState, timeout, 300);
    }
1027358
function(self, e) {
			var self = this;
			var source;

			// Save last active state before modal
			self.lastFocus = self.$elem;

			if ( self.options.should_open === false || ( typeof self.options.should_open === 'function' && self.options.should_open() === false ) ) {
				return;
			}

			// CB: before_open
			self.options.before_open.call(self, e);

			switch (self.options.type) {
				case 'inline':
					self.create_basic();
					break;

				case 'ajax':
					source = self.options.source( self.$elem, self.scope.source );
					self.fetch_ajax( source );
					break;

				case 'confirm':
					self.options.is_locked = true;
					self.create_confirm();
					break;

				case 'image':
					self.create_image();
					break;

				case 'iframe':
					source = self.options.source( self.$elem, self.scope.source );
					self.create_iframe( source );
					break;

				case 'video':
					self.create_video(self.scope.source);
					break;

				case 'instagram':
					self.create_instagram();
					break;
			}

			// call events to be watched (click, tab, keyup, keydown etc.)
			self.watch_events();
		}
664595
function mediaElementLoaded (el) {
  if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
    return;
  }

  // If media specifies autoplay or preload, wait until media is completely buffered.
  return new Promise(function (resolve, reject) {
    if (el.readyState === 4) { return resolve(); }  // Already loaded.
    if (el.error) { return reject(); }  // Error.

    el.addEventListener('loadeddata', checkProgress, false);
    el.addEventListener('progress', checkProgress, false);
    el.addEventListener('error', reject, false);

    function checkProgress () {
      // Add up the seconds buffered.
      var secondsBuffered = 0;
      for (var i = 0; i < el.buffered.length; i++) {
        secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
      }

      // Compare seconds buffered to media duration.
      if (secondsBuffered >= el.duration) {
        // Set in cache because we won't be needing to call three.js loader if we have.
        // a loaded media element.
        // Store video elements only. three.js loader is used for audio elements.
        // See assetParse too.
        if (el.tagName === 'VIDEO') {
          THREE.Cache.files[el.getAttribute('src')] = el;
        }
        resolve();
      }
    }
  });
}
414557
function (callback) {
            async.until(
                // conditions for stopping the poll
                function () {
                    waitTimeOver = elapsed > constants.WAIT_TIMEOUT;
                    return waitTimeOver || domHasChanged;
                },
                function (callback) {
                    // polls the page at an interval
                    setTimeout(function () {
                        elapsed += constants.POLL_INTERVAL;
                        getData.takeSnapshot(page, ph, function (error, page, ph, newDom) {
                            if (error) {
                                callback(error);
                                return;
                            }
                            domHasChanged = helpers.domIsDifferent(originalDom, newDom);
                            callback();
                        });
                    }, constants.POLL_INTERVAL);
                },

                function (error) {
                    if (waitTimeOver) {
                        callback('Timeout while waiting for dom to change');
                        return;
                    }
                    callback(error);
                }
            );
        }
876716
public void waitForElementPresent(final By by, final int maximumSeconds) {
		WebDriverWait wait = new WebDriverWait(driver, maximumSeconds);
		wait.until(ExpectedConditions.presenceOfElementLocated((by)));
	}