js 防抖和節流

印象筆記原文鏈接:https://app.yinxiang.com/fx/183cb733-2e7b-4ea0-a3ad-d62345ae084f

 

一、什麼是防抖和節流

     

 

 

二、區別和使用場景

     

 

 

三、代碼實例 (注意打開控制檯)

   ① 防抖

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>防抖</title>
</head>
<body>
防抖:<input type="text" id="content"/>

<script type="text/javascript">
    var oContent = document.getElementById('content');
    oContent.addEventListener('input', debounce(contentInput, 5000, true));

    function contentInput() {
        console.log('Typing . . . ')
    }

    function debounce(fn, time, triggleNow) {
        var t = null,
            res;

    var debounced = function () {
        var _self = this,
            args = arguments;

        if(t){
            clearTimeout(t);
        }

        if(triggleNow){
            var exec = !t;
            t = setTimeout(function () {
                t = null;
            }, time);

            if(exec){
                res = fn.apply(_self, args);
            }
        } else {
            t = setTimeout(function () {
                res = fn.apply(_self, args);
            }, time);
        }
        return res;
    }

    debounced.remove = function () {
        clearTimeout(t);
        t = null;
    }

    return debounced;
}

</script>
</body>
</html>

 

   ② 節流

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>節流</title>
</head>
<body>
節流:<input type="text" id="content"/>

<script type="text/javascript">
    var oContent = document.getElementById('content');

    oContent.addEventListener('input', throttle(contentInput, 1000));

    function contentInput() {
        console.log('Typing . . . ')
    }

    function throttle(fn, delay) {
        var t = null,
        begin = new Date().getTime();

        return function () {
            var _self = this,
            args = arguments,
            cur = new Date().getTime();

            clearTimeout(t);

            if(cur - begin >= delay){
                fn.apply(_self, args);
                begin = cur;
            } else {
                t = setTimeout(function () {
                    fn.apply(_self, args);
                }, delay)
            }
        }
    }
</script>

</body>
</html>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章