码迷,mamicode.com
首页 > 其他好文 > 详细

函数防抖和节流

时间:2019-07-27 23:41:07      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:body   说明   charset   this   main   char   pat   get   idt   

<!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>

函数防抖和节流

标签:body   说明   charset   this   main   char   pat   get   idt   

原文地址:https://www.cnblogs.com/fazero/p/11257188.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!