是函数防抖就是:
在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时
我们最经常用的就是输入框 搜索、添加等
举个搜索框的例子
<body>
<input type="text" id="text">
</body>
<script>
function _debounce(fn,delay){
var delay = delay || 400
var timer
return function(){
var th = this
var args = arguments
if(timer){
clearTimeout(timer)
}
timer = setTimeout(function(){
timer = null
fn.apply(th,args)
}, delay);
}
}
var txt = document.querySelector('#text').value
txt.addEventListener('input',_debounce(
function(){
console.log(我不是不间断的打印)
}
))
</script>
此时的打印的内容 就不是 你输入一个 打印一个 而是隔了400毫秒 才打印你输入的内容
函数节流:
规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效
function _throttle(fn,delay){
var last;
var timer
var delay = delay || 200
return function(){
var now = +new Date()
var that = this
var arg=arguments
if(last && now-last<delay){
clearTimeout(timer)
timer = setTimeout(function(){
timer = null
last = now
fn.apply(that,arguments)
}, delay);
}else{
last = now
fn.apply(that,arg)
}
}
}
应用场景
_debounce
search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
throttle
鼠标不断点击触发,mousedown(单位时间内只触发一次)
拖拽事件,每拖动1px都会触发onmousemove(可以用throttle优化,每秒触发一次)
盒子跟随鼠标移动
<style>
#box {
width: 100px;
height: 100px;
background-color: skyblue;
position: absolute; //必须要有定位 否则 是实现不了的
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script>
var max = document.getElementById('box')
var doc = document.documentElement
doc.onmousemove = function (e) {
console.log(e);
max.style.left = e.x - 50 + 'px'
max.style.top = e.y - 50 + 'px'
}
</script>