# delay(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: delay(f, s)

{% hint style="success" %}
([](https://lochiwei.gitbook.io/web/js/val/func/kind/higher/decorator "mention")) <mark style="color:orange;">**delay**</mark> the <mark style="color:yellow;">**execution**</mark> of a [..](https://lochiwei.gitbook.io/web/js/val/func "mention")/[method](https://lochiwei.gitbook.io/web/js/val/obj/method "mention") <mark style="color:yellow;">**by s seconds**</mark>.
{% endhint %}

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

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

```javascript
// 📁 delay.js
const { log } = console;

// ⭐️ decorator: "delay"
//    (delay execution by s seconds)
function delay(f, s) {

    // wrapper
    return function wrapper(...args) {

        // delay execution
        setTimeout(

            // ❗ msut use "arrow function" here. 
            // ❗ `this` context is taken from the `wrapper`.
            () => {
                
                // add single-quotes ('') to string arguments
                let arglist = args
                    .map(arg => typeof arg === 'string' ? `'${arg}'` : arg)
                    .join(' ,');
                
                // log execution time, function name, arguments
                log(`${s}: ${f.name}(${arglist}) ...`);

                // ⭐️ forward function call to `f`
                f.apply(this, args);    // ❗ `this` context taken from `wrapper`
            },

            // execute after s seconds
            s * 1000
        );
    }
}

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

{% endtab %}

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

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

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

// function
function f(x) {
  console.log(`   • ${x}`);
}

// object method
const joe = {
    name: 'Joe',
    say(anything) { console.log(`   • ${this.name}: "${anything}"`) },
}

// ❗ delaying method
delay(joe.say, 3)('long time no see!');  // ❗ `this` === undefined (in module context)

// ⭐️ "delay" and "reassign" method
joe.say = delay(joe.say, 4);             // ❗ `this` is still unbound
joe.say('nice to meet you!');            // ⭐️ `this` === `joe` (at call site)

// ⭐️ delaying f function
delay(f, 1)('hello');
delay(f, 2)('world');

// log
// ------------------------------------
// 1: f('hello') ...
//    • hello
// 2: f('world') ...
//    • world
// 3: say('long time no see!') ...
//    • undefined: "long time no see!"   <----  `this` === undefined❗
// 4: say('nice to meet you!') ...
//    • Joe: "nice to meet you!"
```

{% 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/delay-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.
