js/page/debounce.html

60 lines
1.8 KiB
HTML
Raw Permalink Normal View History

2022-02-08 13:50:32 +00:00
<link rel="stylesheet" href="style.css">
<script type="module" src="codeblock.js"></script>
2022-06-09 11:46:42 +00:00
<script type="module" src="scrollToTop.js"></script>
<scroll-to-top>
</scroll-to-top>
2022-02-08 13:50:32 +00:00
2022-06-23 06:59:19 +00:00
<a class="back" href="..">Module Index</a>
2022-02-08 13:50:32 +00:00
<h1 class="js module">debounce.js</h1>
<code-block>import debounce from 'debounce.js'</code-block>
<section>
<h2>Description</h2>
<p>
Utility module for debouncing user-interactions (or any other events).
</p>
<p>
Its main application are cases where expensive operations like updating or querying data are performed in response to some event like a user typing into a search box.
</p>
<dl>
<code>
<dt>debounce</dt>
<dd>target &xrarr; wrapper</dd>
<dd>target, timeout &xrarr; wrapper</dd>
</code>
<dd>
A decorator function that takes a target function and returns a wrapper that will only call the target after a set timeout expires.
Repeatedly calling the wrapper while the timeout is running will reset the timeout without calling the target function.
</dd>
</dl>
<h2>Example</h2>
<code-block>
const update = value =&gt; expensive_operation(value)
input.addEventListener("change", debounce(event =&gt; update(input.value)))
</code-block>
This code will debounce the update event handler of an input element, calling the <code>update</code>
function only after no changes have been made for at least one second.
2022-02-08 14:15:19 +00:00
<h2>Methods</h2>
<p>
The returned wrapper function has the following methods and properties:
2022-02-08 14:15:19 +00:00
<dl>
<dt><code>cancel()</code></dt>
<dd>Cancels the running timeout without calling the target function.</dd>
<dt><code>now(...)</code></dt>
<dd>Cancels the running timeout and calls the target function immediately.</dd>
<dt><code>running</code></dt>
<dd><code>true</code> if there is a timeout currently running, <code>false</code> otherwise.</dd>
2022-02-08 14:15:19 +00:00
</dl>
</p>
2022-02-08 13:50:32 +00:00
</section>