防抖与节流:最基础的性能优化

<!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>
    <input type="button" value="debounce" id="debounce">
    <input type="button" value="throttle" id="throttle">
</body>
<script>
    (function(){
        //防抖
        var timer = false;
        document.getElementById('debounce').onclick = function(){
            clearTimeout(timer);
            timer = setTimeout(function(){
                console.log("防抖,点击后要隔一段时间才执行,在等待期间如果再次点击,则重新计时等待");
            },1000);
        };
        //节流
        var run = true;
        document.getElementById('throttle').onclick = function(){
            if(!run){
                //如果run为false,代表当前时间内不空闲,则不执行
                return;
            }
            run = false;
            setTimeout(function(){
                console.log('节流,在一个时间段内多次触发只执行一次');
                run = true;
            },1000);
        }
        // 函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,
        // 而函数防抖只是在最后一次事件后才触发一次函数。 比如在页面的无限加载场景下,我们需要用户在滚动页面时,
        // 每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。
    }())
</script>
</html>

 

posted @ 2019-06-16 10:20  林不渡  阅读(349)  评论(0编辑  收藏  举报