对速度提升的异步事件KEYUP /电路如何短期连续KEYUP事件(asynchronous keyu

2019-10-17 06:10发布

在网站上,我建设工作,我们有一个搜索栏,用户可以键入搜索存储在数据上的一组元素的各个领域。 这个问题是在较慢的浏览器,当他们开始打字。

我试图做的是下面,用一个jQuery Deferred对象:处理程序中添加一键到输入框。 该KEYUP被触发时,解决任何先前触发keyups仍在“悬而未决”。 然后继续使用当前的keyup事件。 里面的keyup事件本身它在做基于输入值的所有匹配的,它总是会检查当前事件仍悬而未决,如果它不是,它应该跳过该事件的其余部分。

这个问题似乎是,即使缓慢的浏览器,如IE7,每个keyup事件阻止。 因此,如果在“测试”的用户类型,它会尝试完成整个事件的“T”字甚至认为“德”的keyup事件之前,依此类推。

接下来的问题是,我怎么能做出KEYUP事件异步/无阻塞,或者是这几乎是不可能的?

一个例子:

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;
}

在理论上,这应该工作,但正如我所说,它似乎总是阻止。

Answer 1:

而不是做你正在做什么,你可能想寻找到一个名为“反跳”的概念,它基本上可以让你创建一个可调用多次但它并没有被调用一定金额才会完全执行功能的时间。

(下面的代码段是从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);
    };
};

利用这一点,你可能会在用户停止输入后做这样的事情,这将只执行了昂贵的回调为500ms

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

还有由Ben Alman一个很好的插件,提供这个( http://benalman.com/projects/jquery-throttle-debounce-plugin/ ),或LoDash /下划线,如果你正在使用他们提供相同的功能。



文章来源: asynchronous keyup events/how to short circuit sequential keyup events for speed boost