防抖:
<!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">
</body>
<script>
var int = document.querySelector('input')
int.oninput=debounce(task,500)
function task() {
console.log(this.value);
}
function debounce( fn,delay){
var time=null
return function(){
if(time!=null){
clearTimeout(time)
}
time=setTimeout(()=>{
fn.call(this)
},delay)
}
}
</script>
</html>
节流:
<!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>
body {
height: 10000px;
}
</style>
</head>
<body>
</body>
<script>
window.onscroll = throttle(task, 500)
//业务逻辑
function task() {
console.log('触发');
}
//节流函数
function throttle(fn, delay) {
var flag = true;
var time = null;
return function () {
if (flag) {
time = setTimeout(() => {
fn.call(this)// 注:此处需改变this指针,否则业务逻辑中的this指向window
flag = true;
}, delay)
}
flag = false;
}
}
</script>
</html>