美文网首页
防抖与节流

防抖与节流

作者: 糖醋里脊120625 | 来源:发表于2022-10-25 10:40 被阅读0次

一个是多次点击,只触发一次
一个是一个时间段,只触发一次

防抖

任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行
比如:input 输入后发送请求

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="" />
</head>
<style type="text/css">
   
</style>
<body>
    <input id="unDebounce" ></input>
    <script type="text/javascript">
   function ajax(content) {
     console.log('ajax request ' + content)
   }
   function debounce(fun, delay) {
       return function (args) {
           let that = this
           let _args = args
           clearTimeout(fun.id)
           fun.id = setTimeout(function () {
               fun.call(that, _args)
           }, delay)
       }
   }
   let inputb = document.getElementById('unDebounce')
   let debounceAjax = debounce(ajax, 500)
   inputb.addEventListener('keyup', function (e) {
       debounceAjax(e.target.value)
   })
    </script>
</body>

</html>
节流:

规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效

指定时间间隔内只会执行一次任务

懒加载要监听计算滚动条的位置,使用节流按一定时间的频率获取。
用户点击提交按钮,假设我们知道接口大致的返回时间的情况下,我们使用节流,只允许一定时间内点击一次。

 function throttle(fun, delay) {
        let last, deferTimer
        return function (args) {
            let that = this
            let _args = arguments
            let now = +new Date()
            if (last && now < last + delay) {
                clearTimeout(deferTimer)
                deferTimer = setTimeout(function () {
                    last = now
                    fun.apply(that, _args)
                }, delay)
            }else {
                last = now
                fun.apply(that,_args)
            }
        }
    }

    let throttleAjax = throttle(ajax, 1000)

    let inputc = document.getElementById('throttle')
    inputc.addEventListener('keyup', function(e) {
        throttleAjax(e.target.value)
    })

。


相关文章

网友评论

      本文标题:防抖与节流

      本文链接:https://www.haomeiwen.com/subject/ojvnzrtx.html