跳到主要内容

delay [延迟]

TS JS Deno

wait 毫秒后调用提供的函数。

使用 setTimeout() 来延迟执行 fn。

使用扩展运算符 (...) 来向函数提供任意数量的参数。

typescript
const delay = (fn: Func, wait: number, ...args: any[]) =>
setTimeout(fn, wait, ...args);

// Return a promise, Resolve after `wait` milliseconds.
const delayedPromise = (wait: number = 300, ...args: any[]) =>
new Promise((resolve) => {
delay(resolve, wait, ...args);
});
typescript
delay(
function (text) {
console.log(text);
},
1000,
"later"
); // Logs 'later' after one second.

// delayedPromise
let counter = 0;
const updateState = () => {
counter++;
};
const debouncedUpdate = debounce(updateState);
debouncedUpdate(); // counter == 1
debouncedUpdate(); // counter == 1
await delayedPromise(); // counter == 1
assertEquals(counter, 1);