You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中使用setTimeout报错:setTimeout is not a function 求助

解决Node.js中timers/promises导入setTimeout报错问题

问题原因

你遇到的TypeError: setTimeout is not a function是因为错误使用了默认导入,timers/promises模块中的setTimeout是命名导出,而非默认导出。直接默认导入会得到一个包含该函数的对象,而非函数本身,调用自然会报错。

解决方案

1. 修正导入语句

将默认导入改为命名导入,这是最直接的解决方式:

import { setTimeout } from 'timers/promises'

console.log('It will be printed 1-st');

async function newStyleDelay() {
   await setTimeout(5000);
   console.log('It will be printed 3-rd with delay');
}

newStyleDelay();

console.log('It will be printed 2-nd');

2. 确认Node.js版本兼容性

timers/promises模块在Node.js 15.0.0及以上版本才稳定可用,如果你的Node.js版本低于这个版本,需要升级Node.js,或者改用传统setTimeout结合Promise封装的替代方案:

// 手动封装Promise版setTimeout
const setTimeoutPromise = (delay) => new Promise(resolve => setTimeout(resolve, delay));

console.log('It will be printed 1-st');

async function newStyleDelay() {
   await setTimeoutPromise(5000);
   console.log('It will be printed 3-rd with delay');
}

newStyleDelay();

console.log('It will be printed 2-nd');

内容的提问来源于stack exchange,提问作者GP.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:33:10