防抖和节流
html代码
<html lang="en">
<meta charset="UTF-8">
<title>Title
#demo1{
width:100px;
height:100px;
background:chartreuse;
}
#demo2{
width:100px;
height:100px;
background:aqua;
}
<div id="demo1">
<div id="demo2">
<script src="stream.js">
</html>
js代码
let demo1=document.getElementById('demo1');
let demo2=document.getElementById("demo2");
demo1.addEventListener('click',debounce(1,3000));
demo2.addEventListener('click',throttle(2,3000));
//防抖
let count1=0;
function fn1(num) {
demo1.innerHTML=count1++;
console.log(num);
}
function debounce(num,await) {
let timeout;
return function () {
if(timeout){
clearTimeout(timeout)
}
var me=this;
timeout=setTimeout(()=>{
fn1.call(me,num)
},await)
}
}
//节流
let count2=1;
function fn2(num) {
demo2.innerHTML=count2++;
console.log(num);
}
function throttle(num,await) {
let timeout=null;
return function () {
if(timeout)
return;
let me=this;
timeout=setTimeout(()=>{
fn2.call(me,num);
timeout=null;
},await)
}
}
网友评论