title: Why does JS .focus() only work inside a setTimeout of 50ms or longer
body: <h2>Issue</h2>
  
  <p>I am creating a page at work for a client, with a slide out search bar. I want the focus (cursor) to move to the search bar (input) when I click a button that opens the search input field (it starts off hidden).</p>
  
  <p>For some strange reason, the <strong>ONLY</strong> way I can seem to get the focus to switch the the input field is if I put it in a setTimeout with a minimum time of about 50ms (I tried 0, but doesn't work).</p>
  
  <p>Weird caveat - I can momentarily that the input field gets focus/cursor when I close the search bar (click the open/close button that hides the search), but not when it opens, which is what I want. Unless it's in the setTimeout....</p>
  
  <h2>What I've tried</h2>
  
  <p>Setting the focus to something else, then blurring that, then setting the focus to my input field. [x]</p>
  
  <ul>
  <li><p>Wrapping the <code>.focus()</code> in a <code>setTimeout</code> with 0 ms [x]</p></li>
  <li><p>Setting the focus to a different, 'test' input field I created. [WORKS]</p></li>
  <li>Adding <code>tabindex</code> to the input of -1 [x]</li>
  </ul>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const icon = document.getElementById("search-icon");
  const form = document.getElementById("search-form");
  const input = document.getElementById("search-input");
  
  icon.parentElement.addEventListener("click", e =&gt; {
    form.classList.toggle("visible");
    icon.classList.toggle("fa-search");
    icon.classList.toggle("fa-times");  
  
    setTimeout(() =&gt; input.focus(), 50);
  
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="header__search"&gt;
      &lt;i id="search-icon" class="fas fa-search"&gt;click me&lt;/i&gt;
      &lt;form
        id="search-form"
        class="header__search-area"
        onclick="event.stopPropagation()"
      &gt;
        &lt;input
          id="search-input"
          tabindex="-1"
          type="text"
          placeholder="Enter Search Term..."
        /&gt;
        &lt;button type="submit"&gt;search&lt;/button&gt;
      &lt;/form&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>For a quicker understanding, you click the icon (id=search-icon), and it displays the form alongside it which is position absolute and contains the 'input' I want to focus on.</p>
  
  <p>If anyone can explain this, amazing. Google hath provideth nay answers.</p>