# debounce(f, s)

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [technique](https://lochiwei.gitbook.io/web/js/tech) ⟩ [decorator](https://lochiwei.gitbook.io/web/js/val/func/kind/higher/decorator) ⟩ :floppy\_disk: debounce(f, s)

{% hint style="success" %}
([](https://lochiwei.gitbook.io/web/js/val/func/kind/higher/decorator "mention")) <mark style="color:orange;">**suspends**</mark> calls to <mark style="color:blue;">`f`</mark> <mark style="color:yellow;">**until**</mark> there’s <mark style="color:blue;">`s`</mark> <mark style="color:yellow;">**seconds of inactivity**</mark> (no further calls), then <mark style="color:orange;">**invokes**</mark> the <mark style="color:yellow;">**last**</mark> <mark style="color:yellow;">**function call**</mark> (<mark style="color:orange;">**previous calls**</mark>**&#x20;**<mark style="color:yellow;">**are**</mark>**&#x20;**<mark style="color:red;">**ignored**</mark>).&#x20;
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit：[debounce(f, s)](https://replit.com/@pegasusroe/decorator-debouncef-s#debounce.js)
* compare： [debounce-vs.-throttle](https://lochiwei.gitbook.io/web/js/val/func/kind/higher/decorator/debounce-vs.-throttle "mention")

```javascript
// 📁 debounce.js
// ⭐️ decorator: "debounce"
//   (suspends 'f' for 's' seconds)
function debounce(f, s) {

    // log
    console.log(`'${f.name}' has been debounced by ${s} seconds.`)

    // ⭐️ timer id
    let timer;

    // wrapper
    return function wrapper(...args) {
        
        // ⭐️ clear old timer (if it exits)        
        clearTimeout(timer);
        
        // ⭐️ set new timer (in s seconds)
        timer = setTimeout(
            () => f.apply(this, args),
            s * 1000
        );
    }
}

// export
module.exports = { debounce };
```

{% endtab %}

{% tab title="💈範例" %}

* replit：[debounce(f, s)](https://replit.com/@pegasusroe/decorator-debouncef-s#debounce.js)

```javascript
// 📁 index.js
const { debounce } = require('./debounce.js');

// function
function f(...args) {
    let t = Date.now();               // current time
    let T = (t - t0)/1000;            // seconds elapsed from t0
    console.log(T.toFixed(2), args);
}

// ⭐️ debounce `f` (for 2 seconds)
f = debounce(f, 2);

// ⭐️ initial time
let t0 = Date.now();

// ⭐️ call the "debounced" `f`
setTimeout(() => f("a"), 0); 
setTimeout(() => f("b"), 1.5 * 1000); 
setTimeout(() => f("c"), 4.0 * 1000); 

//                 ❌                  ✅                       ✅
//                 a                   b                        c
//  |----- 1.5 --->|─────── 2.0 ──────>|    |─────── 2.0 ──────>|
// (a)            (b)                      (c)
//  |....╷....|....╷....|....╷....|....╷....|....╷....|....╷....|
//  0         1         2         3         4         5         6

// log
// ------------------------------------
// 'f' has been debounced by 2 seconds.
//
// 3.50 [ 'b' ]
// 6.00 [ 'c' ]
```

{% endtab %}

{% tab title="📘 手冊" %}

* [ ] [clearTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout)
* [ ] [setTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)
* [ ] [Date.now()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now) - number of milliseconds elapsed since 1970/1/1 (00:00:00 UTC).
  {% endtab %}

{% tab title="📗 參考" %}

* [x] JS.info ⟩ [Decorators and forwarding, call/apply](https://javascript.info/call-apply-decorators) ⭐️
* [ ] [ydkjs-scope-and-closures-v.2](https://lochiwei.gitbook.io/web/master/ref/book/you-dont-know-js-series-v.2/ydkjs-scope-and-closures-v.2 "mention") ⟩ Ch. 6  (by IIFE, ie. closure)
* [ ] [\[演算法\] Fibonacci：善用 cache 和 Memoization 提升程式效能](https://pjchender.blogspot.com/2017/09/fibonacci-cache-memoization.html) (by parameter)
* [ ] Wictionary ⟩  [memoize](https://en.wiktionary.org/wiki/memoize)&#x20;
  {% endtab %}

{% tab title="👥 相關" %}

* [](https://lochiwei.gitbook.io/web/js/val/func/kind/higher/decorator "mention")
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/val/func/kind/higher/decorator/debounce-f-s.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
