函数防抖
<!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>Document</title>
</head>
<body>
<input type="text" name="" id="">
<script>
input = document.querySelector('input');
input.oninput = antiShake(change,300);
function change(){
console.log('...');
}
function antiShake(cb,time){
var timer;
return function(){
clearTimeout(timer);
timer = setTimeout(function(){
cb();
},time);
}
}
</script>
</body>
</html>
函数节流
<!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>Document</title>
</head>
<body>
<button>函数节流</button>
<script>
var btn = document.querySelector('button');
//console.log(throttle(change,300));
btn.onclick =throttle(change,300);//这里需要得到一个函数,所以throttle必须要返回一个函数;
/* 所以现在按钮的点击事件不是throttle函数,而是这个函数中return的函数,所以每次点击都是执行的return的那个函数 */
function change(){
console.log('click');
}
function throttle(cb,time){
var flag = true;
return function(){
if(!flag){
return ;
}
flag = false;
setTimeout(function(){
cb();
flag = true;
},time);
}
}
</script>
</body>
</html>