防抖与节流

防抖与节流⭐⭐

防抖---点击多次取最后一次

//样式style
<style>
	*{
        margin: 0px;
        padding: 0px;
        list-style: none;
    }
    /* 防抖 */
    .fd {
        margin: 40px auto;
        cursor: pointer;
        width: 200px;
        height: 200px;
        background-color: lightblue;
        overflow: hidden;
        display: flex;
        justify-content: center;
        flex-direction: column;
    }
    .fd>p {
        margin: 0 auto;
        font-size: 20px;
        font-weight: bold;
        color: bisque;
    }
    .fd>span{
        font-size: 50px;
        line-height: 50px;
        text-align: center;
    }
</style>
//body
<div class="fd">
        <p>防抖</p>
        <span>1</span>
</div>
//js
<script>
    let i = 1;
    let timer = null;
    let arr = ['blur', 'red', 'green', 'pink', '#3434e3']
    let fd = document.querySelector(".fd");
    fd.onclick = function () {
        fd.children[1].innerHTML = i++;//children[1]获取的是span元素
        clearTimeout(timer);
        timer = setTimeout(() => {
            fd.style.backgroundColor = arr[parseInt(Math.random() * 5 + 1)]
        }, 1000)
    }
</script>

防抖效果图

(注:这里颜色只变换了一次,但点击了六次,点击六次期间颜色没有变化)

节流---一段时间触发一次

<style>
.jl {
        margin: 0px auto;
        cursor: pointer;
        width: 200px;
        height: 200px;
        background-color: rgb(176, 113, 212);
        overflow: hidden;
        display: flex;
        justify-content: center;
        flex-direction: column;
    }

    .jl>p {

        margin: 0 auto;
        font-size: 20px;
        font-weight: bold;
        color: bisque;
    }

    .jl>span {
        font-size: 50px;
        line-height: 50px;
        text-align: center;
    }
</style>
<div class="jl">
        <p>节流</p>
        <span>1</span>
</div>
<script>
    let i = 1;
    let flag=true;
    let timer = null;
    let arr = ['blur', 'red', 'green', 'pink', '#3434e3']
    let jl = document.querySelector(".jl");
    jl.onclick = function () {
        jl.children[1].innerHTML = i++;//children[1]获取的是span元素
        if(flag){
            flag=false;
            timer=setTimeout(()=>{
                flag=true
                jl.style.backgroundColor = arr[parseInt(Math.random() * 5 + 1)]
            },1000)
        }
    }
</script>

节流效果图

(注:这里颜色只变换了多次,但一秒时间内颜色只变化了一次)

其他的防抖与节流

1.`loadsh防抖与节流`
	_.debounce(fn, time) //防抖
	_.throttle(fn, time) //节流

posted @   残星落影  阅读(80)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
欢迎阅读『防抖与节流』
点击右上角即可分享
微信分享提示