1.1-函数防抖
- 函数防抖:单位时间内,频繁触发事件,只会触发最后一次
- 函数防抖实际开发应用场景: 实时获取输入框文本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" placeholder="请输入文本">
<script>
let timeID = null
document.querySelector('input').oninput = function(){
clearTimeout(timeID)
timeID = setTimeout(()=>{
console.log(`发送ajax请求,搜索内容为${this.value}`)
},500)
}
</script>
</body>
</html>
1.2-函数节流
- 函数节流:单位时间内,频繁触发事件,只会触发一次
- 函数节流应用场景 : 解决高频事件,频繁触发事件浪费性能
方案一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body{
width: 3000px;
height: 3000px;
}
</style>
</head>
<body>
<script>
let lastTime = null
window.onscroll = function(){
let currentTime = Date.now()
if( currentTime - lastTime >= 500 ){
console.log('执行滚动条事件处理代码')
lastTime = currentTime
}
}
</script>
</body>
</html>
方案二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮</button>
<script>
let flag = true
document.querySelector('button').onclick = function () {
if (!flag) {
return
}
flag = false
setTimeout(function () {
console.log('ok')
flag = true
}, 1000)
}
</script>
</body>
</html>