JavaScript在onclick执行节流函数无效

这段函数为什么不执行?

return function() {
      var context = this;
      var args = arguments;
      var now = Date.now();
      console.log('now == ', now)
      if (now - prev >= delay) {
        func.apply(context, args);
        prev = Date.now();
      }
    }

网页所有代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div>
    <div class="test01">点击</div>
  </div>
</body>

<script>
  // 节流throttle代码(定时器):
  var throttle = function(func, delay) {
    var prev = Date.now();
    console.log('prev == ', prev)
    return function() {
      var context = this;
      var args = arguments;
      var now = Date.now();
      console.log('now == ', now)
      if (now - prev >= delay) {
        func.apply(context, args);
        prev = Date.now();
      }
    }
  }
  function handle() {
    console.log(Math.random());
  }

  document.querySelector('.test01').onclick = function() {
      throttle(handle, 5 * 1000)
  }
</script>

</html>
阅读 1.5k
1 个回答
document.querySelector('.test01').onclick = throttle(handle, 5 * 1000)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题