Can I delay the keyup event for jquery?

天涯浪子 提交于 2019-12-05 01:12:09

it can be easily done like this:

var autocomplete = $('#searchinput').typeahead().on('keyup', delayRequest);

function dataRequest() {
    // api request here
}

function delayRequest(ev) {
    if(delayRequest.timeout) {
        clearTimeout(delayRequest.timeout);
    }

    var target = this;

    delayRequest.timeout = setTimeout(function() {
        dataRequest.call(target, ev);
    }, 200); // 200ms delay
}

In general, this can be achieved with setTimeout and clearTimeout methods:

var timer;

$('#textbox').keyup(function() {
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout('alert("Something cool happens here....");', 500);
});

setTimeout will execute the provided javascript after the specified interval in milliseconds passes. clearTimeout will cancel this execution.

I've also prepared jsFiddle demo showing the code snippet in action.

References:

For people working with v0.11 of typeahead.js and using Bloodhound to fetch remote suggestions, you can use the rateLimitWait option to throttle requests:

var search = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: '/search?q=%QUERY',
    rateLimitWait: 500
  }
});

Not sure what version Bootstrap 2.0 uses for typeahead, but v0.9.3 has a minLength option that's hidden under the hood, but not documented.

$('#people').typeahead({
  name: 'people',
  prefetch: './names.json',
  minLength: 3
});

As found from this blog post: http://tosbourn.com/2013/08/javascript/setting-a-minimum-length-for-your-search-in-typeahead-js/

Rather than a delay, if you just want to allow the user to enter a few characters before the ajax $.getJSON request, you could amend the if statement so that the user has to enter a minimum number of characters, for example 3, before you request the data:

if( !self.data('active') && self.val().length >=3){
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!