函数的防抖与节流

记一次账号验证优化

函数防抖(debounce)是指在一定时间内,在动作被连续频繁触发的情况下,动作只会被执行一次,也就是说当调用动作过n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间,所以短时间内的连续动作永远只会触发一次,比如说用手指一直按住一个弹簧,它将不会弹起直到你松手为止。

<!DOCTYPE html>
<html lang="zh">
    <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></title>
        <style>
            #container {
                width: 100%;
                height: 200px;
                background: #ddd;
            }
        </style>
    </head>
    <body>
        <div id="container">
        </div>
        
        <script>
            function debounce(func, waitTime) {
                var timeout;
                return function() {
                    var context = this,
                        args = arguments;
                    if (timeout) {
                        clearTimeout(timeout);
                    }
                    timeout = setTimeout(function() {
                        func.apply(context, args)
                    }, waitTime);
                }
            }

            function num() {
                console.log(1)
            }
            var container = document.querySelector('#container')
            container.onmousemove = debounce(num, 500)
        </script>
    </body>
</html>

函数节流是指一定时间内执行的操作只执行一次,也就是说即预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新周期,一个比较形象的例子是如果将水龙头拧紧直到水是以水滴的形式流出,那你会发现每隔一段时间,就会有一滴水流出。

<!DOCTYPE html>
<html lang="zh">
<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></title>
    <style>
        .container{
            width: 100%;
            height:300px;
            background: #ddd;
        }
    </style>
</head>
<body>
    <div class="container">
        
    </div>
    <script>
        //throttle
        function throttle(func,waitTime){
            var content,args,previous = 0,start=0,timer=null;
            return function(){
                var now = + new Date();
                context = this
                args = arguments
                if(!start){
                    start=now
                }
                if(now-previous>waitTime){
                    func.apply(context,args);
                    previous = now
                }else{
                    clearTimeout(timer)
                    timer = setTimeout(function(){
                        func.apply(content,args)
                    },waitTime)
                }
            }
        }
        function num(){
            console.log(123)
        }
        var container = document.querySelector('.container')
        container.onmousemove = throttle(num,2000)
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/xpcool/p/10330295.html