节流和防抖都是对高频触发事件的优化 ,去减少资源的浪费,提高前端性能
运用场景:input输入事件,滚动条的scroll事件,改变窗口大小...
注意点:下面的两段代码都触发了闭包,如果不知道闭包是什么,建议先了解
关于js闭包的简单介绍https://blog.csdn.net/weixin_66130560/article/details/137219603?spm=1001.2014.3001.5501
防抖
防抖: 在一段持续的时间内,重复触发同一事件,我们让它只执行最后一次触发的事件
用箭头函数写防抖,有一个问题:this的指向。这个问题目前我还没解决,所以用普通函数写防抖
适用场景:input输入事件等
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text">
</body>
<script>
let oInput=document.querySelector('input')
function debounce(fn,delay){
let t=null
return function(){
if(t!==null){
clearTimeout(t)
}
t=setTimeout(()=>{
fn.call(this) //改变fn的this指向,让其指向input框
},delay)
}
}
oInput.oninput=debounce(function () {
console.log(this.value);
},1000)
</script>
</html>
节流
节流: 在规定时间n秒内执行一次,n 秒之后又再执行一次,重复...所以它可能不止执行一次
比如控制每2秒执行一次,那如果输入一段话用了10秒,则它会执行5次
适用场景:滚动条的scroll事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div style="height: 1200px;"></div>
</body>
<script>
window.onscroll=throttle(function(){
alert('这是广告')
},2000)
function throttle(fn,delay){
let t=true
return function(){
if(t){
setTimeout(()=>{
fn.call(this)
t=true
},delay)
}
t=false //因为有个定时器,所以 t=false比t=true先执行,这样的话,下次执行throttle,t=true
}
}
</script>
</html>
如果还没懂,可以去b站找“小k师兄”,真的讲的简单易懂,太喜欢他的这个js合集了
如果本文对你有帮助,希望能得到你的点赞或收藏或关注,这是对我最好的鼓励;
如你有问题或疑惑,欢迎在评论区写下,必将努力解答;
如本文有误区,希望你不吝赐教,让我们共勉!