我可以延迟jquery的keyup事件吗?

前端之家收集整理的这篇文章主要介绍了我可以延迟jquery的keyup事件吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用rottentomatoes电影API结合twitter的类型头插件使用引导2.0.我已经能够整理API,但是我遇到的问题是,每个keyup事件之后,API被调用.这一切都很好,但是我宁愿在一个小暂停之后拨打电话,让用户首先输入几个字符.

这是我当前的代码,在一个keyup事件之后调用API:

var autocomplete = $('#searchinput').typeahead()
    .on('keyup',function(ev){

        ev.stopPropagation();
        ev.preventDefault();

        //filter out up/down,tab,enter,and escape keys
        if( $.inArray(ev.keyCode,[40,38,9,13,27]) === -1 ){

            var self = $(this);

            //set typeahead source to empty
            self.data('typeahead').source = [];

            //active used so we aren't triggering duplicate keyup events
            if( !self.data('active') && self.val().length > 0){

                self.data('active',true);

                //Do data request. Insert your own API logic here.
                $.getJSON("http://api.rottentomatoes.com/api/public/v1.0/movies.json?callback=?&apikey=MY_API_KEY&page_limit=5",{
                    q: encodeURI($(this).val())
                },function(data) {

                    //set this to true when your callback executes
                    self.data('active',true);

                    //Filter out your own parameters. Populate them into an array,since this is what typeahead's source requires
                    var arr = [],i=0;

                    var movies = data.movies;

                     $.each(movies,function(index,movie) {
                        arr[i] = movie.title
                        i++;
                     });

                    //set your results into the typehead's source 
                    self.data('typeahead').source = arr;

                    //trigger keyup on the typeahead to make it search
                    self.trigger('keyup');

                    //All done,set to false to prepare for the next remote query.
                    self.data('active',false);

                });

            }
        }
    });

是否可以设置一个小的延迟,并避免在每次加密后调用API?

解决方法

它可以很容易地这样做:
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
}
原文链接:https://www.f2er.com/jquery/176007.html

猜你在找的jQuery相关文章