throttle
创建限制调用到指定间隔的节流函数
260 bytes
since v12.1.0
使用方法
throttle 函数创建一个新函数,当被调用时,在指定的时间间隔内最多只执行一次原始函数。这对于限制函数触发的速率很有用,特别是对于性能密集型操作,如处理滚动或调整大小事件。
该函数接受两个参数:
- 一个选项对象:
interval:函数调用之间的最小时间(以毫秒为单位)trailing(可选):如果为 true,在节流期间如果函数被调用,则在节流期后也调用该函数
- 要被节流的函数
返回的节流函数还包括这些方法:
isThrottled(): boolean:检查当前是否有活动的节流trigger(...args): void:调用包装函数而不等待下一个间隔
import * as _ from "radashi";
// 节流滚动事件处理程序const handleScroll = () => { console.log("Scroll position:", window.scrollY);};const throttledScroll = _.throttle({ interval: 200 }, handleScroll);window.addEventListener("scroll", throttledScroll);
// 节流API调用const throttledFetch = _.throttle( { interval: 5000, trailing: true }, async () => { const response = await fetch("https://api.example.com/data"); const data = await response.json(); console.log(data); });
// 检查是否节流console.log("Is throttled:", throttledFetch.isThrottled());时机
当 interval 设置为 200ms 时节流行为的可视化表示:
Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -Throttle Invocations: x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x - - -Source Invocations: x - - - - - - - - - - - - x - - - - - - - - - - - - - x - - - - - -当 trailing 选项设置为 true 时,如果在节流时间内进行了任何调用,则在节流期后会发生额外的调用:
Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -Throttle Invocations: x x x x x x x x x x x x x x x x x x x x x - - - - - - - - - - - - -Source Invocations: x - - - - - - - - - - - - x - - - - - - - - - - - - - x - - - - - -在此图中,‘x’表示函数调用,’-‘表示时间流逝。