timers
import { Render, TypeScriptExample } from "~/components";
Use node:timers APIs to schedule functions to be executed later.
This includes setTimeout for calling a function after a delay,
setInterval for calling a function repeatedly,
and setImmediate for calling a function in the next iteration of the event loop.
export default { async fetch(): Promise { console.log("first"); const { promise: promise1, resolve: resolve1 } = Promise.withResolvers(); const { promise: promise2, resolve: resolve2 } = Promise.withResolvers(); timers.setTimeout(() => { console.log("last"); resolve1(); }, 10);
timers.setTimeout(() => {
console.log("next");
resolve2();
});
await Promise.all([promise1, promise2]);
return new Response("ok");
} } satisfies ExportedHandler;
</TypeScriptExample>
:::note
Due to [security-based restrictions on timers](/workers/reference/security-model/#step-1-disallow-timers-and-multi-threading) in Workers,
timers are limited to returning the time of the last I/O. This means that while setTimeout, setInterval, and setImmediate will defer your function execution
until after other events have run, they will not delay them for the full time specified.
:::
:::note
When called from a global level (on [`globalThis`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis)),
functions such as `clearTimeout` and `setTimeout` will respect web standards rather than Node.js-specific functionality. For complete Node.js
compatibility, you must call functions from the `node:timers` module.
:::
The full `node:timers` API is documented in the [Node.js documentation for `node:timers`](https://nodejs.org/api/timers.html).
这篇文档对你有帮助吗?
谢谢你的反馈!