防抖与节流一要考的

防抖节流傻傻分不清楚概念,总是弄混了,平时还好,要使用的时候google一下就明白了,可是面试要是说反了,那就死翘翘了,对于简单的知识点,分数一定要拿稳。

节流

当持续触发事件时,保证一定时间段内只调用一次事件处理函数(秉着开源节流的生活观,虽然我天天逛某宝,可是限制自己一个月只能买一件,此乃节流)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>节流</title>
</head>
<body>
<div id="app" style="height:600px"></div>
<script>
    window.onload = function() {
       function testFn() {
           console.log('触发')
       }
       function commonFn(value) {
           let time = null
           return function() {
               if (!time) {
                    time = setTimeout(() => {
                        testFn()
                        time = null;
                    }, value);
               }
                
           }
       }
       window.addEventListener('scroll', commonFn(2000))
    }
</script>
</body>
</html>

防抖

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>抖动</title>
</head>
<body>
<div id="app" style="height:1000px"></div>
<script>
    window.onload = function() {
        window.addEventListener('scroll', function() {
            let time = null
            return function(res) {
                clearTimeout(time)
                time = setTimeout(() => {
                    console.log(245)
                }, 1000)
            }
        }());
    }
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/Tiboo/p/11795788.html