函数的防抖:
debounce = (func, delay) => {// 防抖 触发后 N秒才执行 如果在N秒内又出发, 则重新计时 主要用于 search let id = null; return function (args) { args.persist(); let that = this, _args = args; clearTimeout(id); id = setTimeout(function () { func.call(that,_args); }, delay); } }
函数的节流:
_throttle = (func, delay) => {// 节流 规定一个时间内 只能处触发一次,如果规定时间内多次触发 ,只有第一次生效 // 定时器版本 let time = Date.now(); return function(args){ args.persist(); let that = this, _args = args; let now = Date.now(); if(now - time > delay) { func.call(that,_args); time = Date.now(); } }
// 定时器版本 // let id = this.id, th = this; // return function(args){ // let that = this, _args = args; // // 不能用id=null 来判断 因为每次setstate都会重新 设置id=null // let bol = !id; // if(bol) {func.call(that,_args);} // if(!th.id) th.id = setTimeout(function(){ // th.id = null; // id = null; // },delay) // } }