js,节流

143 阅读1分钟
import { Http } from './http';const http = new Http();class SingCart {    constructor() {        this.instance = null;        this.record = {};    }    static getInstance() {        if (!this.instance) {            this.instance = new SingCart()        }        return this.instance;    }    add(goods_id, group_id, num) {        let key = `${goods_id}${group_id}`;        if ( key in this.record) {            this.record[key].num = num + 1;        } else {            this.record[key] = new Cart(num, 1)        }    }    reduce(goods_id, group_id, num) {        let key = `${goods_id}${group_id}`;        if ( key in this.record) {            this.record[key].num = num > 0 ? num - 1 : 0;        } else {            this.record[key] = new Cart(num, 0)        }    }    send(goods_id, group_id) {        let key = `${goods_id}${group_id}`;        let _this = this;        if (this.record[key].num == this.record[key].originNum) {            delete this.record[key]            return;        }        return new Promise((resolve, reject) => {            http.sendPostRequest("cart/updateCartByGoodsId", {                goods_id: goods_id,                num: _this.record[key].num,                is_selected: 1,                activity_goods_id: 0,                group_id: group_id            })            .then(res => {                delete this.record[key];                resolve(res)            })            .catch(err => {                reject(err)            })        })    }    getProductNum(goods_id, group_id) {        let key = `${goods_id}${group_id}`;        return this.record[key].num || 0;    }    getProductOriginNum(goods_id, group_id) {        let key = `${goods_id}${group_id}`;        return this.record[key].originNum || 0;    }}class Cart {    constructor(num, type) { // type: 1 + ; 0-        this.originNum = num;        if (type == 1) {            this.num = num + 1;        } else {            this.num = num - 1;        }    }}export  {    SingCart}

debounce (fn, interval = 500) {    var timer;    return function () {      clearTimeout(timer);      let context = this;      let args = arguments;//保存此处的arguments,因为setTimeout是全局的,arguments不是防抖函数需要的。      timer = setTimeout(function() {        fn.call(context, ...args);      }, interval);    }  }