Note that there are some explanatory texts on larger screens.

plurals
  1. POIdiomatic jQuery delayed event (only after a short pause in typing)? (aka timewatch/typewatch/keywatch)
    text
    copied!<p>Here is some jQuery for a search box that I expect is actually an antipattern, and am sure there is a much better solution for that I would love to be pointed towards:</p> <p>I will describe it in comments then just give the code, since the comments may be more clear and simple than the code:</p> <ul> <li>// set up a function call on keypress.</li> <li>// function call has a delay before the main event occurs. </li> <li>// When keypress function is called, wipe any previously queued events and make a new one at the standard delay rate.</li> <li>// Use a global to store the setTimeout pointer.</li> <li>// clearTimeout any pre-existing pointers.</li> <li>// Start a new delay.</li> </ul> <p>The Code:</p> <pre><code> // set up a filter function call on keypress. $('#supplier-select-filter').keypress(function (){ // Currently, resets a delay on an eventual filtering action every keypress. filterSuppliers(.3, this); }); // Delayed filter that kills all previous filter request. function filterSuppliers(delay, inputbox){ if(undefined != typeof(document.global_filter_trigger)){ clearTimeout(document.global_filter_trigger); // clearTimeout any pre-existing pointers. } // Use a global to store the setTimeout pointer. document.global_filter_trigger = setTimeout(function (){ var mask = $(inputbox).val(); $('#user_id').load("supplier.php?action=ajax_getsuppliers_html&amp;mask="+escape(mask)); }, 1000*delay); // Finally, after delay is reached, display the filter results. } </code></pre> <h1>The problems:</h1> <p>On an input box where a search term may consist of 10 characters on average, that's 10 calls to setTimeout in a half a second, which seems to be processor heavy, and in my testing is causing some noticeable performance issues, so hopefully there's a cleaner alternative?</p> <p>.load() is simpler than taking in JSON and then generating html from the json, but maybe there is a better tool?</p> <p>.keypress() doesn't seem to always trigger on things like backspace deletion and other essentials, so perhaps using keypress() on this input box isn't the ideal?</p>
 

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