Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You should look into the <a href="https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout" rel="noreferrer"><code>setTimeout</code></a> and <a href="https://developer.mozilla.org/en-US/docs/DOM/window.clearTimeout" rel="noreferrer"><code>clearTimeout</code></a> functions:</p> <pre><code>$(function() { var timer; $("#id").on('keyup',function() { timer &amp;&amp; clearTimeout(timer); timer = setTimeout(postData, 300); }); }); </code></pre> <p>Basically what we're doing is that instead of firing the <code>postData</code> function immediately, we're passing it to <code>setTimeout</code>, so that it fires after a given amount of time (in this case, 300 milliseconds).</p> <p>The <code>setTimeout</code> function returns a timer ID, which we can then pass to <code>clearTimeout</code> to cancel that call from ever running. On every keypress, before we set a new timer, we first check if there's a timer set. If there is, we cancel the old timer before starting a new one.</p> <hr> <p>To further enhance this, you can also <a href="https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest?redirectlocale=en-US&amp;redirectslug=XMLHttpRequest#abort%28%29" rel="noreferrer">abort your AJAX call</a> on every keypress, just in case the user typed something after 300+ milliseconds (after the timer fires, but before the AJAX request returned).</p> <hr> <p><strong>P.S.</strong> You should check out Ben Alman's <a href="http://benalman.com/projects/jquery-throttle-debounce-plugin/" rel="noreferrer">throttle/debounce plugin</a>, which would work perfectly here.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload