函数防抖
<!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>
<style>
*{
margin: 0;
padding: 0;
}
html,body{
height: 300%;
/* background:-webkit-linear-gradient(top left,lightblue,lightgreen,orange ); */
background: #fff;
}
#submit{
margin: 50px;
}
</style>
</head>
<body>
<button id="submit">提交</button>
<script>
/**
* (防抖) 对于频繁触发某个操作 只识别一次
* func 执行函数
* wait number 设置频繁操作的时间
* innediate boolean 默认多次操作,识别最后一次操作
*
* @return
* 可以被调用的 函数
* */
function debounce(func,wait = 300,innediate = false){
let timer = null;
return function anoymous(...params){
let now = innediate && !timer;
clearTimeout(timer); // 每次点击之前都把定时器 清除
// 重新设置定时器
timer = setTimeout(() => {
// 设置为初始状态
timer = null;
!innediate ? func.call(this,...params) : null;
},wait);
// 如果是立即执行
now ? func.call(this,...params) : null;
}
}
function handle(){
// 设置定时器
console.log('ok');
}
// submit.onclick = handle;
submit.onclick = debounce(handle,500,true)
</script>
</body>
</html>
我是Eric,手机号是13522679763

浙公网安备 33010602011771号