名词解释
- 防抖 顾名思义,防止抖动,抬腿一秒钟你抖了100次,那指定是有脑血栓,你要是抬腿后一秒后才抖一次,那才是我们想要的。在一定时间内重复执行某动作,只执行最后一次
- 截流 顾名思义,截断流水的正常状态。有个元素周期表51,一直对你说话,重复的说,搞得你烦死了。这时候,你戴个耳塞,1秒后才听他说的内容,然后又戴上耳塞。这样你听的唠叨的话,就是1秒钟才能听到一次。在一定时间内容重复执行的动作,降低它的执行频次
代码
<!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>
<style>
.div1 {
background-color: red;
margin-top: 10px;
margin-bottom: 10px;
}
.div12 {
background-color: yellow;
margin-top: 30px;
}
.div2 {
background-color: blue;
margin-top: 20px;
}
</style>
</head>
<body>
<input class="input-throttle" type="text">
<div class="input-copy_container">
<div>input的输入值</div>
<div class="input-copy_text"></div>
</div>
<div class="text-cursor"></div>
</body>
<script>
$body=document.querySelector('body')
$textCursor=document.querySelector('.text-cursor')
$inputThrottle=document.querySelector('.input-throttle')
$inputCopyText=document.querySelector('.input-copy_text')
function mousemoveCallback(e) {
console.log('clientX,clientY', 'x'+e.clientX+' y'+e.clientY);
$textCursor.innerText='x'+e.clientX+' y'+e.clientY
}
function inputCallback(e) {
console.log('e :>> ', e.srcElement.value);
$inputCopyText.textContent=e.srcElement.value
}
function debounce(func, wait) {
let timeId=null;
return (...args) => {
if (timeId) {
clearTimeout(timeId)
}
timeId=setTimeout(() => {
func.apply(this, args)
}, wait);
}
}
function throttle(func, wait) {
let timeId=null;
let prevTime=new Date().getTime();
let nowTime;
return (...args) => {
const nowTime=new Date().getTime()
if (nowTime-prevTime>wait) {
prevTime=nowTime
func.apply(this, args)
}
}
}
$inputThrottle.addEventListener('input', throttle(inputCallback, 2*1000))
document.addEventListener('mousemove', throttle(mousemoveCallback, 2*1000))
</script>
</html>