防抖:通过setTimeout的方式,在一定的时间间隔内,将多次出发变成一次出发。
节流:减少一段时间的触发频率
<!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">
<input type="submit" id="input">
</body>
<script>
var btn=document.getElementById('input');
btn.addEventListener('click',debounce(submit),false);
function submit(e){
console.log(1);
}
function debounce(fn){
var t=null;
return function(){
if(t){
clearTimeout(t);
}
t= setTimeout(() => {
fn();
},1000);
}
}
</script>
</html>
对上面的代码进行更改,解决将event对象传入submit,同时修正this,如下:
function submit(e) {
console.log(this)
console.log(e)
console.log(1);
}
function debounce(fn) {
var t = null;
return function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(() => { //必须要使用匿名函数,
fn.apply(this, arguments)
}, 1000);
}
}
解决第一次点击延时问题:
function debounce(fn) {
var t = null;
return function () {
var firstClick = !t;
if (t) {
clearTimeout(t);
}
if (firstClick)
fn.apply(this, arguments);
else t = setTimeout(() => {
t = null
}, 1000);
}
}
节流
var btn = document.getElementById('input');
btn.addEventListener('click', throttle(submit,2000), false);
function submit(e) {
console.log(this)
console.log(e)
console.log(1);
}
function throttle(fn,delay){
var begin=0;
return function(){
var cur=new Date().getTime();
if(cur-begin>delay){
fn.apply(this,arguments);
begin=cur;
}
}
}