{"id":1312,"date":"2013-01-01T21:13:07","date_gmt":"2013-01-01T21:13:07","guid":{"rendered":"http:\/\/www.sitekickr.com\/blog\/?p=1312"},"modified":"2013-01-01T21:15:06","modified_gmt":"2013-01-01T21:15:06","slug":"optimizing-onkeypress-ajax-handlers-javascript","status":"publish","type":"post","link":"https:\/\/www.sitekickr.com\/blog\/optimizing-onkeypress-ajax-handlers-javascript\/","title":{"rendered":"Optimizing onKeyPress AJAX handlers in JavaScript"},"content":{"rendered":"<p>Not everyone has Google&#39;s mega-awesome data center with tens of thousands of servers, servers that allow them to do things like instant live search on-keydown. That&#39;s right, onkeydown, not onkeypress or keyup, which are less frequent events.<\/p>\n<p><a href=\"http:\/\/www.sitekickr.com\/blog\/wp-content\/uploads\/2012\/12\/onkeydown-google-search.jpg\"><img loading=\"lazy\" alt=\"\" class=\"alignright size-full wp-image-1316\" height=\"126\" src=\"http:\/\/www.sitekickr.com\/blog\/wp-content\/uploads\/2012\/12\/onkeydown-google-search.jpg\" title=\"onkeydown-google-search\" width=\"600\" srcset=\"https:\/\/www.sitekickr.com\/blog\/wp-content\/uploads\/2012\/12\/onkeydown-google-search.jpg 600w, https:\/\/www.sitekickr.com\/blog\/wp-content\/uploads\/2012\/12\/onkeydown-google-search-300x63.jpg 300w\" sizes=\"(max-width: 600px) 100vw, 600px\" \/><\/a><\/p>\n<p>For the majority of us, if we implemented such a feature on a site that served even a million visitors per day, it would cripple our server. But, more than that, the repeated AJAX calls would make the site appear to be unresponsive.<\/p>\n<p>It makes me beg the question, does a human really need results that quickly? Perhaps, for live-search, it is appropriate. But, for most applications, simply waiting a 1\/2 second after the visitors last keypress to make the AJAX call would be sufficient. In fact, it might even be ideal.<\/p>\n<p>As usual, one of my recent projects inspired this thought process and, in turn, this post. I was developing a <a href=\"http:\/\/www.universalwebservices.net\/apps\/mortgage-calculator\/\" target=\"_blank\">mortgage calculator<\/a> that produced instant results as you type. But, since one of the calculations was brute force, it took some time to complete. Two things were happening:<\/p>\n<ol>\n<li>As the user typed a numeric value, each keyup event was being trapped, calling an event handler to recalculate the loan figures. This took a good amount of CPU time, and in turn, made the input of the numbers very &quot;choppy&quot;.<br \/>\n\t\t&nbsp;<\/li>\n<li>While the calculations were being made on each keyup, they essentially were incorrect. For example, if a user wanted results for a loan amount of $100,000, they were forced to see the calculations for $1, $10, $100, etc, until they got to $100,000. This was extra processing that just didn&#39;t need to take place.<\/li>\n<\/ol>\n<p>But, I did want the calculations to be live; I wanted to avoid the submit button, and also not force the user to leave the field (onblur) before getting their result. What to do!<\/p>\n<p>It finally hit me that the JavaScript setTimeout method was exactly what I needed. When a key is pressed, I can create a timeout and assign it to a variable. If another key is pressed before that timeout is over, I&#39;ll clear that timeout and create a new one. Essentially, this will only execute the keydown handler code if it has been at least 1\/2 second (in the example below) since the last keydown event.<\/p>\n<p><code>var keyPressTimeout;<br \/>\n\t$(&#39;body&#39;).on(&#39;keydown&#39;, &#39;.liveSearchField&#39;, function() {<br \/>\n\t&nbsp;&nbsp;&nbsp; clearTimeout(keyPressTimeout);<br \/>\n\t&nbsp;&nbsp;&nbsp; keyPressTimeout = setTimeout( function() { <br \/>\n\t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; \/\/ do my live search ajax calls here<br \/>\n\t&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },<br \/>\n\t&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; 500<br \/>\n\t&nbsp;&nbsp;&nbsp; );<br \/>\n\t});<\/code><\/p>\n<p>If someone were to use a live search feature, typing in the word <em>Pneumonoultramicroscopicsilicovolcanoconiosis<\/em> (one of the longest words in the english language), you would save 44 AJAX requests.<\/p>\n<p>Now, imagine that some chemist out there has the patience to do a good search for the chemical name of Titin (the largest known protein). We&#39;re talking about saving 190,000 AJAX requests!<br \/>\n\t<a href=\"http:\/\/ http:\/\/en.wikipedia.org\/wiki\/Longest_word_in_English\" target=\"_blank\"> http:\/\/en.wikipedia.org\/wiki\/Longest_word_in_English<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Not everyone has Google&#39;s mega-awesome data center with tens of thousands of servers, servers that allow them to do things like instant live search on-keydown.&hellip;<\/p>\n","protected":false},"author":1,"featured_media":1320,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"amp_status":""},"categories":[238,5,41],"tags":[170,82,178,42],"_links":{"self":[{"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/posts\/1312"}],"collection":[{"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/comments?post=1312"}],"version-history":[{"count":8,"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/posts\/1312\/revisions"}],"predecessor-version":[{"id":1323,"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/posts\/1312\/revisions\/1323"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/media\/1320"}],"wp:attachment":[{"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/media?parent=1312"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/categories?post=1312"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.sitekickr.com\/blog\/wp-json\/wp\/v2\/tags?post=1312"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}