在实现节流函数中,原生JavaScript无法使用apply函数

为什么第一次成功,然后func就是undefined了?节流怎么传递带参数的函数?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    html {

    }
    .t1 {
      width: 500px;
      height: 200px;
      background: #0C9A9A;
    }
  </style>
</head>
<body>

<div>
  <div class="t1">
    按钮
  </div>
</div>

<script>

  function sayHi(data) {
    console.log(data + new Date().getSeconds())
  }
  function throttle(func, delay) {
    var timer = null;
    return function() {
      var context = this;
      var args = arguments;
      console.log('timer == ')
      if (!timer) {
        timer = setTimeout(function() {
          console.log('func == ', func)
          func.apply(context, args);
          timer = null;
        }, delay);
      }
    }
  }

  window.addEventListener('resize', throttle(sayHi('abc'), 2000))
</script>
</body>
</html>

感谢楼下答疑

function sayHi(data) {
    console.log(data + new Date().getSeconds())
  }
  function throttle(func, delay) {
    var timer = null;
    return function() {
      var context = this;
      var args = arguments;
      console.log('timer == ')
      if (!timer) {
        timer = setTimeout(function() {
          console.log('func == ', func)
          func.apply(context, args);
          timer = null;
        }, delay);
      }
    }
  }

  window.addEventListener('resize', throttle(function(){sayHi('abc')}, 2000))
阅读 1.6k
1 个回答

throttle方法接收一个function,你这传入的是一个已经执行的方法,然后这个方法返回了undefined,就相当于你给throttle传入了undefined,改一下:

window.addEventListener('resize', throttle(function() {sayHi('abc')}, 2000))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题