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

Node.js中指定时间内未触发verify事件如何执行对应回调函数

你可以通过setTimeout注册超时回调,再在verify事件触发时取消该定时器来实现需求,完整代码如下:

console.log("Fetching data.....");

// 注册10秒超时任务
const fetchTimeout = setTimeout(() => {
    console.log("Fetching the data is taking longer than expected");
    // 若超时后需要终止进程可取消注释下面这行
    // process.exit(1);
}, 10000);

// "verify" 事件会在成功找到数据时触发
fetcher.on("verify", function() {
    // 事件触发后清除未执行的超时任务
    clearTimeout(fetchTimeout);
    console.log("Data found!");
    process.exit(1);
});

逻辑说明

  • 程序启动后同时启动10秒倒计时,倒计时结束默认执行超时提示逻辑
  • 若10秒内verify事件被触发,会先执行clearTimeout清除倒计时任务,超时逻辑就不会被执行
  • 多次调用clearTimeout不会抛出异常,即使定时器已经执行过也不会有问题,不需要额外做状态判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:48:01