const throttle = (func, ms = 200) => { let prev = newDate().getTime() returnfunction(...args) { let now = newDate().getTime() if (now - prev >= ms) { func() prev = now } } }
const throttle(fn,wait)=>{ var pre = Date.now(); returnfunction(){ var context = this; var args = arguments; var now = Date.now(); if( now - pre >= wait){ fn.apply(context,args); pre = Date.now(); } } }
定时器方式
1 2 3 4 5 6 7 8 9 10 11 12 13
const throttle(fn,wait)=>{ var timer = null; returnfunction(){ var context = this; var args = arguments; if(!timer){ timer = setTimeout(function(){ fn.apply(context,args); timer = null; },wait) } } }