防抖: 触发事件后在n秒内只能触发一次,如果在n秒内又触发,则重新计算时间。
应用场景: 用户输入间隔多久后没有输入时进行检查
节流:连续触发事件时在n秒内只能触发一次
应用场景: 需要稀释执行效率的地方使用,例如懒加载的时候监听滚动条。
代码:
<!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>防抖和节流</title>
</head>
<body>
<!-- 参考于:https://www.jianshu.com/p/c8b86b09daf0 -->
<div id="content" style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;"></div>
<script>
let num = 1;
let content = document.getElementById('content');
function count() {
console.log(this)
content.innerHTML = num++;
};
content.onmousemove = debounce(count,2000,true);
// 防抖 所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
// 应用场景: 用户输入间隔多久后没有输入时进行检查
/**
* @desc 函数防抖
* @param func 函数
* @param wait 延迟执行毫秒数
* @param immediate true 表立即执行,false 表非立即执行
*/
function debounce(func,wait,immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
else {
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
}
// 节流 所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。
// 应用场景: 需要稀释执行效率的地方使用,例如懒加载的时候监听滚动条。
/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行毫秒数
* @param immediate true 表示立即执行,false 表示非立即执行
*/
function throttle(func, wait ,immediate) {
if(immediate==true){
var previous = 0;
}else if(immediate==false){
var timeout;
}
return function() {
let context = this;
let args = arguments;
if(immediate===true){
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(immediate===false){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}
</script>
</body>
</html>
壹题github与更多解答地址