节流与防抖

参考学习:https://blog.csdn.net/sml115/article/details/81280101
https://www.cnblogs.com/walls/p/6399837.html
https://blog.csdn.net/hupian1989/article/details/80920324

函数节流和函数防抖,两者都是优化高频率执行js代码的一种手段。
函数防抖是指频繁触发的情况下,只有足够的空闲时间,才执行代码一次。
(用户注册时候的手机号码验证和邮箱验证,只有等用户输入完毕后,前端才需要检查格式是否正确)
(频繁操作点赞与取消点赞)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	
	<style>
    * {
        padding: 0;
        margin: 0;
    }

    .box {
        width: 800px;
        height: 1200px;
    }
</style>
</head>
<body>
    <div class="container">
        <div class="box" style="background: tomato"></div>
        <div class="box" style="background: skyblue"></div>
        <div class="box" style="background: red"></div>
        <div class="box" style="background: yellow"></div>
    </div>
    <script>
        window.onload = function() {
            const decounce = function(fn, delay) {
                let timer = null

                return function() {
                	console.log(this)
                    const context = this
                    console.log(context)
                    let args = arguments
                    console.log(args)
                    clearTimeout(timer) // 每次调用debounce函数都会将前一次的timer清空,确保只执行一次
                    timer = setTimeout(() => {
                        fn.apply(context, args)
                    }, delay)
                }
            }

            let num = 0

            function scrollTap() {
                num++
                console.log(`看看num吧 ${num}`)
            }
            // 此处的触发时间间隔设置的很小
            document.addEventListener('scroll', decounce(scrollTap, 5000))
            document.addEventListener('scroll', scrollTap)
        }
    </script>
</body>
</html>

函数节流是指一定时间内js方法只跑一次。
(一般是onrize,onscroll等这些频繁触发的函数)

   (定时器实现)
const throttle = function(fn,delay) {
              let timer = null
              return function() {
                const context = this
                let args = arguments
                if(!timer) {
                  timer = setTimeout(() => {
                    fn.apply(context,args) 
                    clearTimeout(timer) 
                  },delay)
                }
              }
            }
(时间戳实现)
 const throttle2 = function(fn, delay) {
          let preTime = Date.now()

          return function() {
              const context = this
              let args = arguments
              let doTime = Date.now()
            
              if (doTime - preTime >= delay) {
                  fn.apply(context, args)
                  preTime = Date.now()
              }
          }
        }

鼠标移动事件 onmousemove, 滚动滚动条事件 onscroll, **窗口大小改变事件https://mp.csdn.net/mdeditor/89408348#**onresize,瞬间的操作都会导致这些事件会被高频触发。 如果事件的回调函数较为复杂,就会导致响应跟不上触发,出现页面卡顿,假死现象。 在实时检查输入时,如果我们绑定 onkeyup事件发请求去服务端检查,用户输入过程中,事件的触发频率也会很高,会导致大量的请求发出,响应速度会大大跟不上触发。

posted @ 2019-04-19 21:21  princeness  阅读(131)  评论(0编辑  收藏  举报