防抖:多次触发某一个事件只关注第一次或最后一次
节流:多次触发时间保证一定时间内一定产生一次结果
防抖立即执行版本
<body>
<style>
div {
height: 200px;
width: 200px;
background-color: red;
}
</style>
</head>
<body>
<div id="d1"></div>
<script>
//立即执行版本
// var d1 = document.getElementById('d1');
// var handle = function(e) {
// console.log(100)
// }
// function debounce(func, wait) { //防抖函数
// var timeout = null;
// return function() {
// var context = this;
// var arg = arguments; //event 事件e参数 点击事件会有一个e参数
// if (timeout) {
// clearTimeout(timeout)
// }
// var callNow = !timeout;
// timeout = setTimeout(function() {
// timeout = null
// }, wait)
// if (callNow) {
// func.apply(context, arg)
// }
// }
// }
// d1.addEventListener('click', debounce(handle, 1000))
</script>
</body>
防抖延迟执行版本
<body>
<style>
div {
height: 200px;
width: 200px;
background-color: red;
}
</style>
</head>
<body>
<div id="d1"></div>
<script>
// var d1 = document.getElementById('d1');
// var handle = function(e) {
// console.log(100)
// }
// var d1 = document.getElementById('d1')
// var handle = function() {
// console.log(1)
// }
// function debounce(func, wait) {
// var timeout = null
// return function() {
// var content = this
// var args = arguments
// if (timeout) {
// clearTimeout(timeout)
// }
// timeout = setTimeout(function() {
// func.apply(content, args)
// }, wait)
// }
// }
// d1.addEventListener('click', debounce(handle, 1000))
</script>
</body>
时间戳版本节流(立即执行版本)
<body>
<div id="d1"></div>
<script>
var d1 = document.getElementById('d1')
function handle() {
console.log(1)
}
function throttle(func, wait) {
var previous = 0
return function() {
var now = Date.now()
var content = this
var args = arguments
if (now - previous > wait) {
func.apply(content, args)
previous = now
}
}
}
d1.addEventListener('click', throttle(handle, 1000))
</script>
</body>
延迟执行版本
<body>
<div id="d1"></div>
<script>
var d1 = document.getElementById('d1')
function handle() {
console.log(1)
}
function throttle(func, wait) {
var timeout = null
return function() {
var content = this
var args = arguments
if (!timeout) {
timeout = setTimeout(() => {
timeout = null
func.apply(content, args)
}, wait)
}
}
}
d1.addEventListener('click', throttle(handle, 1000))
</script>
</body>