节流:
频繁触发,但是触发时间内一段时间执行一次
常见应用场景:
resize scroll
//理解版
<body>
<input type="text">
<script>
const ipt = document.querySelector('input')
// 节流:一定时间内执行一次
let timer = null
ipt.oninput = (e) => {
if (!timer) {
timer=setTimeout(() => {
console.log(e.target.value);
timer = null
}, 2000);
}
}
</script>
</body>
// 时间戳,第一次触发立即执行
function throttle(fn, interval) {
let last = 0
return function () {
let now = Date.now()
// now - last两次触发的时间间隔
if (now - last >= interval) {
last = now
fn.apply(this, arguments);
}
}
}
function handle() {
console.log(Math.random());
}
const throttleHandle = throttle(handle, 1000)
throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()
// 定时器,第一次触发不会立即执行,但是最后一次会延迟
function throttle(fn, interval) {
let timer = null
return function () {
let context = this
let agrs = arguments
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, agrs)
timer = null
}, interval)
}
}
}
function handle() {
console.log(Math.random());
}
const throttleHandle = throttle(handle, 1000)
throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()
// 定时器+时间戳,第一次触发不会立即执行,最后一次也不会延迟
function throttle(fn, delay) {
let timer = null
let startTime = Date.now()
return function () {
let curTime = Date.now()
//curTime - startTime本次执行和上次执行的时间差
//delay - (curTime - startTime)是否到达设定时间
let remainning = delay - (curTime - startTime)
let context = this
let args = arguments
clearInterval(timer)
if (remainning <= 0) {
fn.apply(context, agrs)
startTime = Date.now()
} else {
timer = setTimeout(fn, remainning)
}
}
}
function handle() {
console.log(Math.random());
}
const throttleHandle = throttle(handle, 1000)
throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()
throttleHandle()