成长(7/2000)——面试题合集4
2021-06-11 本文已影响0人
Kiki_Q
防抖和节流
防抖概念
当我们在输入框输入内容的时候,没变化一个文字都会触发更新,这不是我们想要的,这样的变化太频繁,我们可以在事件触发后延迟一定时间再执行,比如我们在持续输入后5秒执行(5秒内输入会重新计时),那么基本输入完后执行了1次,这就是我们防抖的概念
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta charset="UTF-8">
</head>
<body>
<input type="text" id="input">
<script src="./jquery.js"></script>
<script>
function debounce(delay,callback) {
let timer;
return function(value) {
timer? clearTimeout(timer): null;
timer = setTimeout( function() {
callback(value)
},delay)
}
}
let doF = function (value) {
console.log(value)
}
let debounceFun = debounce(1000,doF);
$('#input').keyup((e)=>{
debounceFun(e.target.value)
})
</script>
</body>
</html>
实际应用
- ecahrts当浏览器改变宽高的时候,希望重新渲染
- 输入搜索
节流概念
当触发一个事件需要一定时间,那么一定时间内再触发需要等待;(一段时间只做一件事情)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta charset="UTF-8">
</head>
<body>
<button id="btn">提交</button>
<script src="./jquery.js"></script>
<script>
function throttle(delay,callback) {
let timer;
return function(value) {
if(!timer){ //当定时器不存在,空出任务,加入新的任务
timer = setTimeout( function() {
callback(value)
timer = null; //执行完任务,timer重置
},delay)
}
}
}
let doF = function (value) {
console.log(value)
}
let throttleFun = throttle(1000,doF);
$('#btn').on('click',()=>{
throttleFun('123')
})
</script>
</body>
</html>
实际应用
- 表单的提交
鼠标不断点击触发,规定在n秒内多次点击只有一次生效
扩展版本
1.立即执行和非立即执行的防抖函数封装
2.定时器和时间戳版本的节流函数封装
3.这里的this指向问题,例如我们调用的时候是执行此函数content.onmousemove = throttle(count,1000,true); 即content.onmousemove = 返回的闭包函数,这时候this只是定义,但this真正的指向是执行的时候确定的,这里面对象.方法中,对象是window,所以this执向的是window
function debounce(func, delay, immediate) {
let timer;
return function () {
let context = this, //this指向
args = arguments;
if (timer) clearTimeout(timer);
if (immediate) {
let callFlag = !timer;
timer = setTimeout( () => {
timer = null;
}, delay);
if( callFlag ) func.apply(context, args);
} else {
timer = setTimeout( () => {
func.apply(context, args);
}, delay);
}
}
}
function throttle(func, delay, type) {
if (type === 1) { //定时器版本 //2为时间戳版本
let timer;
}else {
let previous = 0
}
return function () {
let context = this,
args = arguments;
if (type === 1) {
if(!timer){
timer = setTimeout( () => {
func.apply(context, args);
timer = null;
}, delay)
}
}else {
let now = Date.now();
if( now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
}
实战练习
- 防抖和节流都是运用了闭包的思想
- 瀑布流中运用了防抖和节流(图片懒加载运用了节流提升了性能;窗口重置,利用了防抖的思想。)