To enable built-in Node.js APIs and polyfills, add the nodejs_compat compatibility flag to yourWrangler configuration file. This also enables nodejs_compat_v2 as long as your compatibility date is 2024-09-23 or later.Learn more about the Node.js compatibility flag and v2.
Usenode:timers ↗ APIs to schedule functions to be executed later.
This includessetTimeout ↗ for calling a function after a delay,setInterval ↗ for calling a function repeatedly,andsetImmediate ↗ for calling a function in the next iteration of the event loop.
importtimers from"node:timers";exportdefault{asyncfetch(){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();});awaitPromise.all([promise1,promise2]);returnnewResponse("ok");},};importtimers from"node:timers";exportdefault{asyncfetch():Promise<Response>{console.log("first");const{promise:promise1,resolve:resolve1}=Promise.withResolvers<void>();const{promise:promise2,resolve:resolve2}=Promise.withResolvers<void>();timers.setTimeout(()=>{console.log("last");resolve1();},10);timers.setTimeout(()=>{console.log("next");resolve2();});awaitPromise.all([promise1,promise2]);returnnewResponse("ok");}}satisfiesExportedHandler<Env>;Due tosecurity-based restrictions on timers 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 executionuntil after other events have run, they will not delay them for the full time specified.
When called from a global level (onglobalThis ↗),functions such asclearTimeout andsetTimeout will respect web standards rather than Node.js-specific functionality. For complete Node.jscompatibility, you must call functions from thenode:timers module.
The fullnode:timers API is documented in theNode.js documentation fornode:timers ↗.