title: SpinWait.SpinUntil taking MUCH longer than timeout to exit while waiting for Selnium element to exist
body: <p>I have a relatively simple method to wait until an element exists and is displayed. The method handles the situation where more than a single element is returned for the given By (usually we only expect one of them to be displayed but in any case the method will return the first displayed element found).</p>
  <p>The issue I'm having is that when there is no matching element on the page (at all), it is taking magnitudes of time more* than the TimeSpan specified, and I can't figure why.</p>
  <p>*I just tested with a 30s timeout and it took a little over 5m</p>
  <p>code:</p>
  <pre><code>    /// &lt;summary&gt;
      /// Returns the (first) element that is displayed when multiple elements are found on page for the same by
      /// &lt;/summary&gt;
      public static IWebElement FindDisplayedElement(By by, int secondsToWait = 30)
      {
          WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(secondsToWait);
          // Wait for an element to exist and also displayed
          IWebElement element = null;
          bool success = SpinWait.SpinUntil(() =&gt;
          {
              var collection = WebDriver.FindElements(by);
              if (collection.Count &lt;= 0)
                  return false;
              element = collection.ToList().FirstOrDefault(x =&gt; x.Displayed == true);
              return element != null;
          }
          , TimeSpan.FromSeconds(secondsToWait));
  
          if (success)
              return element;
          // if element still not found
          throw new NoSuchElementException(&quot;Could not find visible element with by: &quot; + by.ToString());
      }
  </code></pre>
  <p>You would call it with something like this:</p>
  <pre><code>    [Test]
      public void FindDisplayedElement()
      {
         webDriver.Navigate().GoToUrl(&quot;https://stackoverflow.com/questions&quot;);
         var nonExistenetElementBy = By.CssSelector(&quot;#custom-header99&quot;);
         FindDisplayedElement(nonExistenetElementBy , 10);
      }
  </code></pre>
  <p>If you run the test (with 10s timeout) you will find it takes about 100 seconds to actually exit.</p>
  <p>It looks like it might have something to do with the mix of the inherit wait built into WebDriver.FindElements() wrapped inside a SpinWait.WaitUntil().</p>
  <p>Would like to hear what you guys think about this conundrum.</p>
  <p>Cheers!</p>