jQuery keypress() handler: managing flow of events
<p>I've got some jQuery code to focus a <code>&lt;select&gt;</code> dropdown based on user input, <a href="http://stackoverflow.com/questions/4599504/html-select-focus-option-based-on-user-input">as per a previous question</a>. Here it is:</p>

<p><strong>HTML</strong></p>

<pre><code>&lt;select id="poetslist"&gt;
    &lt;option value="shakespeare" data-initial="WS"&gt;William Shakespeare&lt;/option&gt;
    &lt;option value="milton" data-initial="JM"&gt;John Milton&lt;/option&gt;
    &lt;option value="keats" data-initial="JK"&gt;John Keats&lt;/option&gt;
    &lt;option value="wordsworth" data-initial="WW"&gt;William Wordsworth&lt;/option&gt;
    &lt;option value="larkin" data-initial="PL"&gt;Phillip Larkin&lt;/option&gt;
&lt;/select&gt;
</code></pre>

<p><strong>JavaScript</strong></p>

<pre><code>    $("#userlist").keypress(function (e) {
        initials += String.fromCharCode(e.which).toUpperCase();
                // when the relevant initials are typed, select that item
        $(this).find("option").filter(function () {
            return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
        }).first().attr("selected", true);
        $('#book_results').html(loading_img); // Show 'loading' gif
                // Then use get_books function to update some HTML on the page with relevant info
        get_books($(this).find("option").filter(function () {
            return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
        }).first().val(), null, null);      
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(function () {
            timer = null;
            initials = "";
        }, 2000); // Max 2 second pause allowed between key presses
        return false;
    });
</code></pre>

<p>It's very promising, but I'm finding that when the user types e.g. 'WW', "William Shakespeare" is selected first, and all the HTML on the page updates for him, and only after a couple of seconds does the dropdown 'catch up' and update for "William Wordsworth". </p>

<p>I'm certain that this is my fault for not handling the flow of events correctly, but could anyone suggest a fix? N.B. I can't guarantee that every item will have two initials. </p>

<p>Thanks for helping out a JavaScript novice!</p>
