美文网首页
自制简易throttle函数

自制简易throttle函数

作者: kofzx | 来源:发表于2019-06-06 17:26 被阅读0次

throttle.js

/**
 * 防止连续点击的函数
 * @param {function} func 需要执行的函数
 * @param {number} delay 多久后才能接着点
 */
const throttle = function(func, delay) {
  let isClick = true, // 是否可点击
      timer = null;
  return function() {
    if (!timer) {
      timer = setTimeout(() => {
        isClick = true;
        clearTimeout(timer);
        timer = null;
      }, delay);
    }
    if (!isClick) return false;  
    isClick = false;
    // this为调用throttle处的作用域
    // 同时保证arguments传参
    func.apply(this, arguments);
  };
};

test.html

<!DOCTYPE html>
<html>
<head>
    <title>test my throttle</title>
</head>
<body>
    <button onclick="test()">test</button>
    <script src="./throttle.js"></script>
    <script>
        // 1秒内不会重复触发
        const test = throttle(function() {
            console.log('test exec');
        }, 1000);
    </script>
</body>
</html>

这样连点就不会重复触发函数了

微信截图_20190606174735.png

相关文章

网友评论

      本文标题:自制简易throttle函数

      本文链接:https://www.haomeiwen.com/subject/vgvuxctx.html