加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax延迟插件

发布时间:2020-12-16 01:48:24 所属栏目:百科 来源:网络整理
导读:最近遇到需要做ajax延迟的需求,上一段代码记录下: var XHRService = function(options) { this.options = options; this.reqTimer = null;};XHRService.prototype = { constructor: XHRService,req: function(options) { var that = this,defer = $.Deferr

最近遇到需要做ajax延迟的需求,上一段代码记录下:

var XHRService = function(options) {
    this.options = options;
    this.reqTimer = null;
};

XHRService.prototype = {
    constructor: XHRService,req: function(options) {
        var that = this,defer = $.Deferred();

        clearTimeout(this.reqTimer);
        this.reqTimer = setTimeout(function() {
            that._req(options,defer);
        },this.options.reqDelay);

        return defer.promise();
    },_req: function(options,defer) {
        var that = this;

        if (this.xhr) {
            this.xhr.abort();
        }

        if (typeof this.options.before === 'function') {
            clearTimeout(this.loadingTimer);
            this.loadingTimer = setTimeout(function() {
                that.options.before();
            },this.options.loadingDelay);
        }

        this.xhr = $.ajax(options).done(function(data) {
                defer.resolve(data);
            })
            .always(function(res,status,xhrObj) {
                clearTimeout(that.loadingTimer);

                if (typeof that.options.after === 'function') {
                    that.options.after();
                }

                if (xhrObj === that.xhr) {
                    that.xhr = null;
                }
            });
    }
};
var xhr = new XHRService({
    reqDelay: 10,loadingDelay: 10,before: function() {
        console.log('show loading...');//显示loadingbar
    },after: function() {
        console.log('hide loading...');//隐藏loadingbar
    }
});
 xhr.req({
        url: url,dataType: 'json'
    }).done(function(data) {
        console.log('done!');
    });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读