Throttle event calls in jQuery

前端 未结 7 838
自闭症患者
自闭症患者 2020-11-27 03:52

I have a keyup event bound to a function that takes about a quarter of a second to complete.

$(\"#search\").keyup(function() {
  //code that tak         


        
相关标签:
7条回答
  • 2020-11-27 04:25

    Here's a clean way of doing it with JQuery.

        /* delayed onchange while typing jquery for text boxes widget
        usage:
            $("#SearchCriteria").delayedChange(function () {
                DoMyAjaxSearch();
            });
    
        */
        (function ($) {
            $.fn.delayedChange = function (options) {
                var timer;
                var o;
    
                if (jQuery.isFunction(options)) {
                    o = { onChange: options };
                }
                else
                    o = options;
    
                o = $.extend({}, $.fn.delayedChange.defaultOptions, o);
    
                return this.each(function () {
                    var element = $(this);
                    element.keyup(function () {
                        clearTimeout(timer);
                        timer = setTimeout(function () {
                            var newVal = element.val();
                            newVal = $.trim(newVal);
                            if (element.delayedChange.oldVal != newVal) {
                                element.delayedChange.oldVal = newVal;
                                o.onChange.call(this);
                            }
    
                        }, o.delay);
                    });
                });
    
    
            };
    
            $.fn.delayedChange.defaultOptions = {
                delay: 1000,
                onChange: function () { }
            }
    
            $.fn.delayedChange.oldVal = "";
    
    
        })(jQuery);
    
    0 讨论(0)
提交回复
热议问题