防抖?节流?这可能是最好的图解了

本篇文章主要是对 Glossary + Explain Like I'm Five中防抖和节流部分的翻译(来自谷歌)。

个人认为这是对节流和防抖最好的解释的文章之一。文章的其他部分也值得去看。

What is debouncing and throttling?

Debouncing and throttling are too common techniques for dealing with things that happen "too often". Imagine you're meeting a friend, and they are telling you a story, but they struggle to pause when talking. Let's say you want to accommodate them while also responding to what they have to say, when possible. (I know this might be a bit contrived, but bear with me!)

Debouncing 和 throttling 是处理“过于频繁”发生的事情的常用技术。想象一下,你正在和一个朋友见面,他们正在给你讲一个故事,但他们说话时很难停下来。假设您想在可能的情况下容纳他们,同时还要回应他们的意见。 (我知道这可能有点做作,但请耐心等待!)

Let's say you can never speak at the same time. You have a few strategies:

假设在同一时间你不能说话。你有几个策略:

Synchronous 同步

You could respond to each sentence the moment they finish it:

你可以在他们完成的那一刻回应每句话:

5

This might work okay if your responses are short. But if your responses are longer, this could make it very hard for them to finish the story. So this strategy isn't great.

如果您的回复很简短,这可能会奏效。但是如果你的回答更长,这可能会让他们很难完成这个故事。所以这个策略不是很好。

Debounced 防抖

You could wait for them to stop talking. For example, if they pause for long enough, you could start responding:

你可以等他们停止说话。例如,如果他们暂停的时间足够长,您可以开始响应:

image.png

This strategy works well if your friend is occasionally making pauses. However, if they're talking for a few minutes without a pause, this doesn't let you respond at all:

如果您的朋友偶尔停顿一下,则此策略很有效。但是,如果他们在没有停顿的情况下讲了几分钟,这根本不会让您做出回应:

image.png

Throttled 节流

You could decide to respond at most once a minute. Here, you keep count of how long you haven't spoken for. Once you haven't spoken for a minute, you insert your response right after the friend's next sentence:

您可以决定最多每分钟响应一次。在这里,您可以计算自己有多久没有说话了。一旦你一分钟没说话,你就在朋友的下一句话之后插入你的回答:

image.png

This strategy is helpful if your friend wants you to respond as they go, but they don't ever create pauses for you to do it. But it's not great if they're creating pauses but you're still waiting out for no reason:

如果您的朋友希望您在他们进行时做出回应,则此策略很有用,但他们永远不会为您制造停顿。但是,如果他们制造停顿,但您仍然无缘无故地等待,那就不好了:

image.png

总结

防抖:在事件被触发 n 秒后 , 再次执行回调 ; 如果 n 秒内触发 , 重新计时 ;

节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率

其他相关文档

おすすめ

転載: juejin.im/post/7066311360111443998