asynchronous keyup events/how to short circuit sequential keyup events for speed boost

℡╲_俬逩灬. 提交于 2019-12-14 02:36:32

问题


On the website I'm building for work, we have a search bar where the user can type in to search various fields stored in data on a set of elements. The problem comes in slower browsers, when they start typing.

What I was trying to do is the following, using a jQuery Deferred object: add a key up handler to the input box. when the keyup is triggered, resolve any previously triggered keyups that are still 'pending'. then continue on using the current keyup event. Inside the keyup event itself where it's doing all the matching based on the input value, it always checks to see if the current event is pending still, and if it's not, it is supposed to skip the remainder of that event.

The problem seems to be that, even with slow browsers like IE7, each keyup event is blocking. So if the user types in "testing", it'll try to finish the entire event for the "t" character before it even sees the keyup event of "te", and so on.

The question then becomes, how can I make the keyup events asynchronous/non-blocking, or is this pretty much impossible?

An example:

var search_values = new Array();
var deferred_searches = {};

function filterSearchResults(event) {
    var input_element = jq(event.target);
    var search_value = input_element.val();
    console.log('user just typed final letter in :' + search_value);
    for (var svi = 0; svi < search_values.length-1; svi++) {
        if (deferred_searches[search_values[svi]] !== undefined &&
            deferred_searches[search_values[svi]].state() == 'pending') {
            console.log('resolving ' + search_values[svi])
            deferred_searches[search_values[svi]].resolve(search_values[svi]);
        }
    }

    var result_list = jq('div#header_project_selection_result_list');
    var all_project_results = result_list.find('div.header_project_result');

    console.log('beginning search for "'+search_value+'"');
    if (search_value == '') {
        // Blank input value means show all results
    }
    else {
        // Non-blank value means search
        if (! startSearchFilter(search_value, all_project_results)) {
            return false; // this should return out of this current event handler
        }
    }
    console.log('ending search for "'+search_value+'"');
},

/**
 * Helper function that actually handles finding and hiding/showing results,
 * and highlighting found text.
 *
 * Uses jQuery for this functionality.
 *
 * @param       search_value                            string              The text the user has input
 * @param       all_project_results                     jQuery              A jQuery extended array of all project results to filter
 *
 * @return      tbr                                     boolean             Flag indicating whether the search was short circuited
 */
function startSearchFilter(search_value, all_project_results) {
    var tbr = true;

    search_values.push(search_value);
    deferred_searches[search_value] = jq.Deferred();
    deferred_searches[search_value].done(function(sv) {
        search_values = search_values.without(sv);
        console.log('done deferred search for "'+sv+'" - disabling');
    });

    var number_of_results_found = 0;
    var pr_count = all_project_results.length - 1;
    var regexp = new RegExp(search_value, 'im');
    for (var index = 0; index <= pr_count; index++) {
        if (deferred_searches[search_value].state() == 'pending') {
            // KEEP GOING
            var ext_project_result = all_project_results.eq(index);
            var result_data = ext_project_result.data();

            //console.log(search_value+" is in state '"+deferred_searches[search_value].state()+"'.....' all_project_results.each() [inside]");
            if (result_shown) {
                number_of_results_found++;
                // The input text has been found on data for the current project, so make sure we show that result row
                ext_project_result.addClass('filtered');
            }
            else if (ext_project_result.hasClass('filtered')) {
                // The input text has not been found, or the user is not an admin and can't view it, so hide that row
                ext_project_result.removeClass('filtered');
            }
            continue; // keep going to the next result element
        }
        else {
            tbr = false;
            break; // break when short circuited
        }
    }
    if (deferred_searches[search_value].state() == 'pending') {
        deferred_searches[search_value].resolve(search_value); // explicitly resolve this finalized one
    }

    return tbr;
}

In theory this should work but as I mentioned, it seems to always block.


回答1:


Rather than doing what you're doing, you might want to look into a concept called "debounce" which basically allows you create a function that can be invoked multiple times but will only fully execute once it hasn't been invoked for a certain amount of time.

( The following code snippet is from underscore.js )

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
var debounce = function(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) {
                func.apply(context, args);
            }
        };
        if (immediate && !timeout) {
            func.apply(context, args);
        }

        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

Using that, you might do something like this which will only execute our expensive callback 500ms after the user stops typing

$( "#searchbox" ).keyup( debounce(function() {
    // Some expensive operation here
}, 500));

There's a good plugin by Ben Alman that provides this ( http://benalman.com/projects/jquery-throttle-debounce-plugin/ ), or LoDash/Underscore provide the same functionality if you're using them.



来源:https://stackoverflow.com/questions/12538344/asynchronous-keyup-events-how-to-short-circuit-sequential-keyup-events-for-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!