函数防抖与函数节流

 什么是函数防抖?

       频繁触发,但是只在特定的时间内才执行最后一次触发函数。
       指的是,触发事件后在规定时间内只能执行一次,如果在规定时间内又触发了该事件,则会重新开始算规定时间
                比如:   当你在电梯里面的时候,
                        电梯开始倒数5秒关闭门, 在5秒时间内,突然来了一个人, 门就会自动打开, 电梯就会重新计时5秒,如果在5秒时间内又又来了一个人,电梯就会又重新计时5秒。 开始倒计时 5 4 3 2 1,此时没有人来了,电梯关门开始运行。

function debounce(callback, time = 300) {
        let i;

        return function () {
            clearTimeout(i);

            i = setTimeout(callback, time);

        }

    }

绑定滚动条事件

window.onscroll = debounce(function () {
        console.log("调用了一次");

    }, 500);

具体应用

css:

<style>
    *{
        margin: 0;
        padding: 0;
    }
    body{
        height: 5000px;
        background-color: aqua;
    }
    img{
        position: fixed;
        bottom: 100px;
        right: 50px;
        display: none;
    }
</style>

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    < img id="returntop" src="./img/return.png" alt="">
</body>
</html>

js

<script>
    //函数防抖
    function delbounce(callback,time = 300){
        let t;
        return function(){
            clearTimeout(t);
            t = setTimeout(callback,time);
        }
    }
    //绑定滚动条事件
    window.onscroll = delbounce(returntop,200);
    //onscroll   滚动条事件  属于window事件  不写到标签里
     function returntop(){
        //距离浏览器顶部的距离
        console.log("调用了1次");
        let num = document.body.scrollTop || document.documentElement.scrollTop;
        // console.log(parseInt(num));
        //判断隐藏和出现
        if(parseInt(num) > 400){
            document.getElementById("returntop").style = "display:block";
        }else{
            document.getElementById("returntop").style = "display:none";
        }
    }
</script>

二,节流:

限制一个函数在一定时间内只能执行一次。

为什么需要函数节流

前端开发过程中,有一些事件或者函数,会被频繁地触发(短时间按内多次触发)。

     function throlle(callback,time){
        let lasttime = new Date().getTime();
        return function(){
            let nowtime = new Date().getTime();
            if (nowtime - lasttime > time){
                lasttime = nowtime;
            }
        }
    }
    window.onscroll = throlle(function(){
        console.log("调用了1次");
    },500);

实际使用:

css


<style>
    *{
        margin: 0;
        padding: 0;
    }
    body{
        background: url(./img/login.gif) no-repeat;
        background-size: 100%;
    }
    div.login{
        width: 500px;
        height: 360px;
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 10px;
        margin: 50px auto;
    }
    div.login h1{
       padding-top: 10px;
       padding-bottom: 10px;
       text-align: center;
       color: white;
    }
    div.email,div.tel,div.pwd{
        margin-left: 17px;
    }
    div.login div.email input,div.login div.tel input,div.login div.pwd input{
        width: 450px;
        height: 45px;
        padding-left: 11px;
        margin: 8px 0;
    }
    div.login div.btn button{
        width: 450px;
        height: 40px;
        color: white;
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 20px;
        text-align: center;
        margin-top: 10px;
        margin-left: 20px;
        line-height: 40px;
        border: 0;
    }
    div.login div.btn button:hover{
        cursor: pointer;
        background-color:rgba(0, 0, 0, 0.4) ;
    }
    div.login #emailarr,#telarr,#pwdarr{
        color: red;
        font-size: 12px;
    }
</style>

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="login">
        <h1>后台管理系统</h1>
        <div class="email">
            <input type="email" id="email" onblur="isEamil()" placeholder="请输入邮箱..." required><br>
            <div id="emailarr"></div>
        </div>
        <div class="tel">
            <input type="tel" pattern="^1([358][0-9]|4[456789]|66|7[0135678]|9[189])\d{8}$"
             id="tel" onblur="isTel()" placeholder="请输入电话号码..." required><br>
            <div id="telarr"></div>
        </div>
        <div class="pwd">
            <input type="password" pattern="^[0-9a-zA-Z]{6,12}" onblur="isPwd()" id="pwd" placeholder="请输入密码..." required><br>
            <div id="pwdarr"></div>
        </div>
        <div class="btn">
            <button id="btn" disabled>登录</button>
        </div>
    </div>
</body>
</html>

js


<script>
    //功能:表单验证
    let emailState = false;
    let telState = false;
    let pwdState = false;
    //验证邮箱格式是否正确
    function isEamil(){
        let email = document.getElementById("email");
        if(email.validity.valueMissing){
            email.style = "border:2px red solid";
            document.getElementById("emailarr").innerHTML = "* 邮箱不能为空!";
            emailState = false;
            isState();
            return false;
        }
        if(email.validity.typeMismatch){
            email.style = "border:2px red solid";
            document.getElementById("emailarr").innerHTML = "* 请输入正确的邮箱!";
            emailState = false;
            isState();
            return false;
        }
 
        email.style = "border:2px green solid";
        document.getElementById("emailarr").innerHTML = "";
        emailState = true;
        isState()
        return true;
 
    }
    //验证电话号码格式是否正确
    function isTel(){
        let tel = document.getElementById("tel");
        if(tel.validity.valueMissing){
            email.style = "border:2px red solid";
            document.getElementById("telarr").innerHTML = "* 电话号码不能为空!";
            telState = false;
            isState();
            return false;
        }
 
        if(tel.validity.patternMismatch){
            tel.style = "border:2px red solid";
            document.getElementById("telarr").innerHTML = "* 请输入正确的电话号码!";
            telState = false;
            isState();
            return false;
        }
 
        tel.style = "border:2px green solid";
        document.getElementById("telarr").innerHTML = "";
        telState = true;
        isState()
        return true;
 
    }
    //验证密码格式是否正确
    function isPwd(){
        let pwd = document.getElementById("pwd");
        if(pwd.validity.valueMissing){
            pwd.style = "border:2px red solid";
            document.getElementById("pwdarr").innerHTML = "* 密码不能为空!";
            pwdState = false;
            isState();
            return false;
        }
 
        if(pwd.validity.patternMismatch){
            pwd.style = "border:2px red solid";
            document.getElementById("pwdarr").innerHTML = "* 请输入正确的密码!";
            pwdState = false;
            isState();
            return false;
        }
        pwd.style = "border:2px green solid";
        document.getElementById("pwdarr").innerHTML = "";
        pwdState = true;
        isState()
        return true;
    }
    //判断三个结果是否都为true  removeAttribute()  删除获取的的某个节点的对应属性
    function isState(){
        if(emailState && telState && pwdState){
            document.getElementById("btn").removeAttribute("disabled");
        }else{
            document.getElementById("btn").setAttribute("disabled","disabled");//设置属性
        }
    }
 
    //登陆成功
    function login(){
        console.log("函数调用1次");
        //将数据发给后台处理
        //后台返回两种结果 error  success
        //将成功后的用户信息进行本地存储  userid  token
        // let userid = 123456;
        // localStorage.setItem("userid",userid);
        // location.href = "./logininfo.html";
    }
 
    document.getElementById("btn").onclick = throlle(login,5000);
 
    function throlle(callback,time){
        let lasttime = new Date().getTime();
        return function(){
            let nowtime = new Date().getTime();
            if (nowtime - lasttime > time){//在time时间段  不能在调用函数
                callback();
                lasttime = nowtime;
            }
        }
    }
</script>

函数节流函数防抖都是为了减少目标函数的频繁执行,特别是那些计算量较大、耗费性能较多的函数函数节流适用于大量事件按照时间均匀触发的情况,而函数防抖适用于多次事件只需要响应一次的情况。 函数节流的实现方式主要是通过设置一个定时器,在指定的时间间隔内只执行一次目标函数。当事件触发时,如果定时器已经存在,则不执行目标函数,并重新开始计时,直到定时器到期后执行目标函数。这样可以将大量事件按照时间均匀分配触发,减少频繁执行目标函数的情况。 而函数防抖的实现方式是设置一个定时器,在指定的时间间隔内只执行一次目标函数。当事件触发时,如果定时器已经存在,则清除定时器并重新开始计时,直到定时器到期后执行目标函数。这样可以避免多次事件触发时频繁执行目标函数,只在最后一次事件触发后执行目标函数。 在JavaScript中,函数节流函数防抖可以通过编写相应的函数来实现。函数节流可以通过设置一个定时器,在指定的时间间隔内执行目标函数函数防抖可以通过设置一个定时器,在指定的时间间隔内只执行一次目标函数。 总结来说,函数节流函数防抖是为了减少频繁执行目标函数而设计的技术,在不同的场景中选择合适的方式可以提升性能和用户体验。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [js函数节流,js函数防抖](https://blog.csdn.net/MFWSCQ/article/details/100130519)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [js中的函数防抖函数节流](https://blog.csdn.net/m0_52900946/article/details/124778757)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值