防抖
<!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>
<input type="text" id="input">
<script>
/**
* 如果keyup中的函数不使用箭头函数,使用function (){}的方式
* 只要在keyup函数中调用callback函数时,改变this的指向
* 就能直接使用this.value输出文本框的值
*/
var inputText = document.getElementById('input')
inputText.addEventListener('keyup', keyup(() => {
console.log(inputText.value);
// console.log(this.value);
}, 1000))
function keyup(callback, time) {
let aa = null
return function () {
if (aa) {
clearTimeout(aa)
}
aa = setTimeout(() => {
callback && callback()
// callback.apply(this, arguments)
aa = null
}, time)
}
}
</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>节流</title>
<style>
div {
width: 100px;
height: 100px;
background-color: orange;
}
</style>
</head>
<body>
<div id="div" draggable="true">
</div>
<script>
var div = document.getElementById('div')
div.addEventListener('drag', drag((e) => {
console.log(this);
console.log(e.offsetX + ' ' + e.offsetY);
}, 1000))
function drag(callback, time) {
let aa = null
return function () {
if (aa) { return }
aa = setTimeout(() => {
// 使用下面这种直接调用callback方式需要传参数e,上面的return function也要传参数e
// callback(e)
// 像下面使用apply之后调用callback就不用传参数e了
callback.apply(this, arguments)
aa = null
}, time)
}
}
</script>
</body>
</html>