debounce限制多长时间才能执行一次,throttle限制多长时间必须执行一次,一个限制上限、一个限制下限

防抖

适用范围 input框实时搜索 防抖

  1. function debounce(func, delay) {
  2. let timeout = null;.//闭包
  3. return function(e) {
  4. if(timeout){
  5. clearTimeout(timeout)
  6. }
  7. var context = this, args = arguments
  8. timeout = setTimeout(function(){
  9. func.apply(context, args);
  10. },delay)
  11. };
  12. };
  13. @@@@ = debounce(fn, 380);

节流

适用范围在 比input, keyup更频繁触发的事件中,如resize, touchmove, mousemove, scroll。throttle 会强制函数以固定的速率执行。因此这个方法比较适合应用于动画相关的场景。

  1. function throttle(fn, threshhold) {
  2. var timeout
  3. var start = new Date;
  4. var threshhold = threshhold || 160
  5. return function () {
  6. var context = this, args = arguments, curr = new Date() - 0
  7. clearTimeout(timeout)//总是干掉事件回调
  8. if(curr - start >= threshhold){
  9. console.log("now", curr, curr - start)//注意这里相减的结果,都差不多是160左右
  10. fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次
  11. start = curr
  12. }else{
  13. //让方法在脱离事件后也能执行一次
  14. timeout = setTimeout(function(){
  15. fn.apply(context, args)
  16. }, threshhold);
  17. }
  18. }
  19. }
  20. var mousemove = throttle(function(e) {
  21. console.log(e.pageX, e.pageY)
  22. });
  23. // 绑定监听
  24. document.querySelector("#panel").addEventListener('mousemove', mousemove);
  25. throttle(fn,delay){
  26. let valid = true
  27. return function() {
  28. if(!valid){
  29. return false
  30. }
  31. var context = this, args = arguments
  32. valid = false
  33. setTimeout(() => {
  34. fn.apply(context, args)
  35. valid = true;
  36. }, delay)
  37. }
  38. }