节流

18 阅读1分钟
//设置背景颜色随机切换函数
   function changeColor() {
       document.body.style.backgroundColor = 'rgba(' + parseInt(Math.random() * 256) + ',' + parseInt(Math.random() * 256) + ',' + parseInt(Math.random() * 256) + ')'
        }

//节流函数
        function throttle(func, wait) {
            let timer;//便于清除
            return function () {//形成闭包函数
                var con = this;//保留this指向
                if (timer) {//避免多个定时器同时开启
                    return;
                }
                clearTimeout(timer);//清除
                timer = setTimeout(function () //定时器{
                    func.call(con);//调用背景比改变函数 并且赋值this
                    timer = null;//定时器走完变成false 才能继续走 否则就return
                }, wait)
            }
        }
        window.addEventListener('mousemove', throttle(changeColor, 2000))//window添加鼠标移动事件 并且传入颜色改变函数 跟 改变时间