函数防抖和节流

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="btn">点我啊</div>
</body>
<script>
    //每wait时间执行一次
    function throttle(func, wait) {
        var timeout = null;
        var previous = null;
        return function () {
            var now = +new Date();
            var context = this;
            if (!previous) {
                previous = now
            }
            //下次触发 func 剩余的时间
            var remaining = wait - (now - previous);
            // 如果小于0,说明离上次触发超过了wait时间,重新算
            if (remaining < 0) {
                remaining = wait
            }
            if (!timeout) {
                timeout = setTimeout(() => {
                    previous = +new Date();
                    timeout = null;
                    func.apply(context, arguments)
                }, remaining);
            }
        };
    }
    ////无论wait时间内执行多少次,只会在最后一次的wait时间后执行
    function debounce(fn, wait) {
        var timeout = null;
        return function () {
            var context = this;
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(() => {
                fn.apply(context, arguments)
            }, wait)
        }
    }
    // function debounce(fn, wait, immediate) {
    //     var timeout = null;
    //     var first = true;
    //     return function () {
    //         var context = this;
    //         if (immediate && first) {
    //             fn.apply(context, arguments)
    //             first = false
    //         }
    //         if (timeout) clearTimeout(timeout);
    //         timeout = setTimeout(() => {
    //             fn.apply(context, arguments)
    //         }, wait)
    //     }
    // }
    function say() {
        var args = Array.prototype.slice.call(arguments)
        console.log(new Date())
        console.log('参数:', args.join(','))
    }
    var a = debounce(say, 3000, true)
    document.getElementById('btn').onclick = () => {
        a('hello', 'world')
    }
</script>

</html>
posted @ 2019-07-27 22:59  樱风凛  阅读(207)  评论(0编辑  收藏  举报