Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a solution along the lines of CMS's, but solves a few key issues for me:</p> <ul> <li>Supports multiple inputs, delays can run concurrently.</li> <li>Ignores key events that didn't changed the value (like Ctrl, Alt+Tab).</li> <li>Solves a race condition (when the callback is executed and the value already changed).</li> </ul> <pre class="lang-js prettyprint-override"><code>var delay = (function() { var timer = {} , values = {} return function(el) { var id = el.form.id + '.' + el.name return { enqueue: function(ms, cb) { if (values[id] == el.value) return if (!el.value) return var original = values[id] = el.value clearTimeout(timer[id]) timer[id] = setTimeout(function() { if (original != el.value) return // solves race condition cb.apply(el) }, ms) } } } }()) </code></pre> <p>Usage:</p> <pre class="lang-js prettyprint-override"><code>signup.key.addEventListener('keyup', function() { delay(this).enqueue(300, function() { console.log(this.value) }) }) </code></pre> <p><em>The code is written in a style I enjoy, you may need to add a bunch of semicolons.</em></p> <p>Things to keep in mind:</p> <ul> <li>A unique id is generated based on the form id and input name, so they must be defined and unique, or you could adjust it to your situation.</li> <li><strong>delay</strong> returns an object that's easy to extend for your own needs.</li> <li>The original element used for delay is bound to the callback, so <code>this</code> works as expected (like in the example).</li> <li>Empty value is ignored in the second validation.</li> <li>Watch out for <strong>enqueue</strong>, it expects milliseconds first, I prefer that, but you may want to switch the parameters to match <code>setTimeout</code>.</li> </ul> <p>The solution I use adds another level of complexity, allowing you to cancel execution, for example, but this is a good base to build on.</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. This table or related slice is empty.
    1. This table or related slice is empty.
    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