<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>programming on Reorx’s Forge</title><link>https://reorx.com/tags/programming/</link><description>Recent content in programming on Reorx’s Forge</description><image><url>https://reorx.com/images/forge-v2-compat.svg</url><link>https://reorx.com/images/forge-v2-compat.svg</link></image><generator>Hugo -- gohugo.io</generator><lastBuildDate>Thu, 21 Dec 2023 20:23:46 +0800</lastBuildDate><atom:link href="https://reorx.com/tags/programming/feed.xml" rel="self" type="application/rss+xml"/><item><title>Debounce and Throttle</title><link>https://reorx.com/blog/debounce-and-throttle/</link><pubDate>Thu, 21 Dec 2023 20:23:46 +0800</pubDate><guid>https://reorx.com/blog/debounce-and-throttle/</guid><description>介绍 Debounce 和 Throttle 两种频率限制手段，以具体场景为例展示两者的区别。</description><content:encoded><![CDATA[<h2 id="概念">概念</h2>
<p>Debounce 和 Throttle 是两种相似的频率限制手段。Debounce 顾名思义，去掉弹跳/抖动，能看出防止误操作的意味；Throttle 的意思是节流阀，更加直接了当。作为两种常见的设计模式，理解他们的工作原理和细微区别能够帮助我们写出更健壮的应用程序。</p>
<p>虽然是两个通用的概念，但它们的确主要在 JavaScript 中被提及和使用，究其原因，JavaScript 中常常出现连续发生的大量事件，如果不对调用频率做出限制，会产生严重的性能问题。且这些事件是可以舍弃的，一段时间内只需要产生一次有效调用即可。而在后端则很少出现这种情况，所有的事件都必须要处理，性能问题通常通过异步和分布式调用来解决。</p>
<p>下面是我对这两种设计模式的理解。</p>
<ul>
<li>
<p><strong>Debounce</strong>: 将间隔不超过设定时间的多次连续调用变成一次。</p>
<p>从工作原理上来讲，Debounce 会使目标函数变为延迟生效，当对其进行连续多次调用时，若前后两次调用的时间间隔不超过设定值，则前一次调用会被取消。直到某次调用后，在设定的时间内没有出现下一次调用，那么这次调用将不会被取消，从而最终被执行。</p>
</li>
<li>
<p><strong>Throttle</strong>: 确保一个函数被连续多次调用时，在设定时间内最多只实际执行一次。</p>
</li>
</ul>
<p>放在一起对比的话：</p>
<ul>
<li><strong>相似之处</strong>：Debounce 和 Throttle 都限制了函数执行的最大频率不超过每设定时间一次</li>
<li><strong>不同之处</strong>：在快速（间隔小于设定时间）连续调用时，Throttle 确保了函数会规律执行，但 Debounce 只有当连续调用放缓（间隔大于设定时间）时才会执行。</li>
</ul>
<h2 id="应用场景">应用场景</h2>
<p>设想如下几个场景:</p>
<ol>
<li>当用户改变网页窗口的大小后，调用一个函数以调整 UI 布局</li>
<li>当用户在滚动浏览网页内容时，根据内容所处的位置，持续更新大纲目录中的链接高亮</li>
<li>在一个输入框的下方，让搜索提示结果随着用户的输入持续不断地更新</li>
</ol>
<p>我们一起来看看每个场景分别应用 Debounce 和 Throttle 会有什么样的效果，并评判哪个是更加合适的频率控制方式。</p>
<h3 id="场景-1">场景 1</h3>
<p>用户按住鼠标不松一直改变窗口大小，使用 Debounce 的情况下，UI 在用户停顿或者松开鼠标时才会改变；使用 Throttle 的情况下，用户会观察到 UI 在拖拽窗口大小的过程中每隔一会改变一次，容易给人一种反应迟钝或卡住的错觉，因此 Debounce 是更好的选择。</p>
<h3 id="场景-2">场景 2</h3>
<p>用户持续向下滚动鼠标滑轮，使用 Debounce 的情况下，大纲的高亮只有当用户停止滚动时才会更新。所以当用户一次性滚动很长时，只能看到一次高亮的改变，中间仿佛跳过了一般；而使用 Throttle 的情况下，随着用户滚动，高亮会稳定地以设定的时间间隔更新，因此 Throttle 是更好的选择。</p>
<h3 id="场景-3">场景 3</h3>
<p>用户以较快地速度连续输入字符，使用 Debounce 的情况下，只有当用户停止输入时搜索提示才会更新；使用 Throttle 的情况下，搜索提示会稳定地以设定的时间间隔更新，但如果用户输入最后一个字符的时间，正好处于上一次调用后的间隔期，无法触发新的调用，那么用户所看到的提示就不是根据完整的输入内容做出的。Debounce 由于能够保证函数总是在用户停止输入时执行，是比 Throttle 更好的选择。</p>
<h2 id="库的使用">库的使用</h2>
<p>首选 lodash，因为它是一个非常流行且久经考验的库。但如果不想让整个 lodash 混入项目的构建结果，可以安装 <code>lodash.throttle</code> 和 <code>lodash.debounce</code> 两个独立的库。如果你使用的 bundler 支持 tree-shaking，也可以通过 <code>lodash-es</code> 来 import 这两个函数，最终构建结果中只会包含与之相关的代码。</p>
<p>npm 狂魔 sindresorhus 也维护了两个包，<a href="https://github.com/sindresorhus/debounce">debounce</a> 和 <a href="https://github.com/sindresorhus/throttleit">throttleit</a>, 如果你想要更简洁的实现，可以考虑使用。</p>
<p>下面以 <code>lodash.throttle</code> 为例，展示其如何在一个 TypeScript 项目里安装和使用 :</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">npm i lodash.throttle
</span></span><span class="line"><span class="cl"><span class="c1"># 还需要额外安装 `@types/` 的类型定义</span>
</span></span><span class="line"><span class="cl">npm i -D @types/lodash.throttle
</span></span></code></pre></div><p>引入和调用:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-ts" data-lang="ts"><span class="line"><span class="cl"><span class="kr">import</span> <span class="nx">throttle</span> <span class="kr">from</span> <span class="s1">&#39;lodash/throttle&#39;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kr">const</span> <span class="nx">onScroll</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=</span> <span class="p">{</span><span class="cm">/* 实现细节 */</span><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// onScroll 执行的最高频率为每 100 毫秒一次
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;scroll&#39;</span><span class="p">,</span> <span class="nx">throttle</span><span class="p">(</span><span class="nx">onScroll</span><span class="p">,</span> <span class="mi">100</span><span class="p">));</span>
</span></span></code></pre></div><h2 id="后续思考">后续思考</h2>
<p>这篇笔记来源于<a href="https://t.me/reorx_share/4866">重构 GitHub TOC Sidebar 扩展</a>时对场景 2 的思考，之前用的是自己手写的 Debounce，在滚动过程中经常看不到 ToC 的高亮变化，这次换成了 lodash.throttle，终于达到了预期的效果。其实这三个场景我都在过往的开发经历中遇到过，并且是在不了解这两个概念的情况下独立思考出了（简陋或丑陋的）解决方案，直到最近才重新审视，阅读了相关的文章，学习了更好的实现方式。这也是为什么我在<a href="https://t.me/reorx_share/4864">关于状态机的短文</a>中感叹基础知识的重要性，如果能更早地知道这两个概念，就能避免曾经在黑暗中摸索的痛苦。当然，因为自己琢磨过，当看到更系统更高级的实现时，就会有更深刻的理解，这大概是<a href="https://x.com/noworkforsixian/status/1737122354013360488">这位推友</a>希望自己是通过 Vanilla JS 学习前端的原因。</p>
<div class="tweet social-quote">
  <div class="title">
    <svg role="img" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><title>Twitter</title><path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/></svg>

    
  </div><blockquote class="twitter-tweet" data-dnt="true"><p lang="zh" dir="ltr">如果重学前端，我肯定老老实实地用原生 JS 去完整地做几个项目，去 appendChild，去切身体会一下手动管理一切状态，命令式更新 UI，还要时刻让它和状态保持一致的痛苦。然后再去学框架，把这些项目重写一遍。 很遗憾我没有写过 jQuery，太早接触框架的最大问题就是对它们在解决什么问题理解得不够深刻</p>&mdash; Sixian (@noworkforsixian) <a href="https://twitter.com/noworkforsixian/status/1737122354013360488?ref_src=twsrc%5Etfw">December 19, 2023</a></blockquote>


</div>


<p>一言以蔽之，开发遇到困难免不了自己琢磨，但在琢磨时多想想能否将问题定义出来，符合一个已有的概念，然后去参考现实世界中系统和标准的解决方案；如果没有也无所谓，未来某一刻这种思考过程会化作某种领悟，不会白费。</p>
<h2 id="参考资料">参考资料</h2>
<ul>
<li><a href="https://css-tricks.com/debouncing-throttling-explained-examples/">Debouncing and Throttling Explained Through Examples</a>: css-tricks 的经典老文</li>
<li><a href="https://kettanaito.com/blog/debounce-vs-throttle">Debounce vs Throttle: Definitive Visual Guide</a>: 用动态可交互的方式展现了 Throttle 和 Debounce 的差异，非常推荐阅读</li>
<li><a href="https://underscorejs.org/docs/modules/throttle.html">THROTTLE.JS</a>: underscore 的 throttle 源码</li>
<li><a href="https://lodash.com/docs/4.17.15#debounce">_.debounce</a>: lodash 的 debounce 文档</li>
</ul>
]]></content:encoded></item><item><title>“Moving away from UUIDs”, Really?</title><link>https://reorx.com/essays/2022/11/my-thoughts-on-moving-away-from-uuids/</link><pubDate>Wed, 23 Nov 2022 16:20:31 +0800</pubDate><guid>https://reorx.com/essays/2022/11/my-thoughts-on-moving-away-from-uuids/</guid><description>Recently I saw an article called Moving away from UUIDs – Neil Madden on Hacker News. The title immediately got my attention since I use UUIDs a lot in various projects, no matter personal or commercial. Whether I&amp;rsquo;m using it right or wrong is a vital concern from an engineering perspective, so I read it thoroughly and carefully. This article is my summary and thoughts on it.
Overall, the author gives an opinion that using UUIDs for unguessable random string like session tokens or cookies is a bad practice, the reasons are as follows:</description><content:encoded><![CDATA[<p>Recently I saw an article called <a href="https://neilmadden.blog/2018/08/30/moving-away-from-uuids/">Moving away from UUIDs – Neil Madden</a> on Hacker News. The title immediately got my attention since I use UUIDs a lot in various projects, no matter personal or commercial. Whether I&rsquo;m using it right or wrong is a vital concern from an engineering perspective, so I read it thoroughly and carefully. This article is my summary and thoughts on it.</p>
<p>Overall, the author gives an opinion that using UUIDs for <strong>unguessable random string like session tokens or cookies</strong> is a bad practice, the reasons are as follows:</p>
<ol>
<li>UUID is insecure in cryptography. In some situations, an attacker can take only 35 minutes to brute-force guess a valid result.</li>
<li>UUID is inefficient in storing data. Because of its hexadecimal format and the use of extra dashes, a UUID takes 36 characters to represent 16 bytes of data.</li>
</ol>
<p>As a replacement, the author suggests to use a 20 bytes random string that is <a href="https://en.wikipedia.org/wiki/Base64#URL_applications">URL-safe base64</a>-encoded. Here&rsquo;s an example comparing with an UUID string:</p>
<pre tabindex="0"><code>20 bytes base64 random: Xl3S2itovd5CDS7cKSNvml4_ODA
UUID                  : 5a097fe7-1720-457c-8363-8d660a65bab2
</code></pre><p>The advantages over UUIDs are:</p>
<ol>
<li>A 20 bytes random value is almost impossible to guess in a reasonable time.</li>
<li>The length of the string is just 224 characters, resulting in much less storage space than UUIDs.</li>
</ol>
<p>Generally speaking, I think although the conclusion of not using UUIDs for tokens is correct, the assumption is totally wrong. UUID (Universally unique identifier) as the name says, is an ID which should not be used for cryptographic purposes in the first place. The proper scenario for UUIDs is using it as primary keys in distributed systems, in which it prevents collisions without relying on a centralized identity generator. In contrast, random string has no way to achieve that.</p>
<p>I did learn something new from this article, but it failed to give me anything useful upon my understanding of how UUIDs should be used.</p>
<p>Do not write clickbait posts, as being neutral and accurate is a virtue for engineers.</p>
]]></content:encoded></item></channel></rss>