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

Node.js中使用setTimeout的JavaScript异步问题排查

终端答题超时后后续题目自动超时问题

我实现了一个终端答题功能,导入JSON格式的题目供用户作答,用户有5秒时间回答,超时后自动切换到下一题。目前遇到的问题是:当计时器触发超时后,即使用户输入答案,后续的题目也会自动触发超时。

日志示例

Definition: A term used to describe a file or directory location on a drive
1. name
2. separator
3. path
4. prompt
 > 
Please answer within 5 seconds
Definition: A term used to describe a file or directory location on a drive
1. name
2. separator
3. path
4. prompt
 > 3
Please answer within 5 seconds
Definition: A term used to describe a file or directory location on a drive
1. name
2. separator
3. path
4. prompt
 > 3
Correct

Complete: Score - 2/2

我的代码

async function vocabularyDrillMode() {
    const definitions = loadJsonFile('definitions.json');
    let score = 0;
    const defBegin = definitions.length;

    async function drillTerm(currentDefinition) {
        console.log(`Definition: ${currentDefinition.definition}`);
        currentDefinition.possibleTerms.forEach((term, index) => console.log(`${index + 1}. ${term}`));

        return new Promise((resolve) => {
            const timer = setTimeout(() => {
                resolve({ success: false, term: "timeout" });
            }, 5000);

            rl.question(" > ", (userAnswer) => {
                clearTimeout(timer);

                const selectedAnswer = parseInt(userAnswer, 10) - 1;

                // 检查用户是否输入'q'退出
                if (userAnswer.toLowerCase() === "q") {
                    resolve({ success: false, term: "q" });
                } else if (!isNaN(selectedAnswer) && selectedAnswer >= 0 && selectedAnswer <= 3) {
                    // 用户输入有效数字答案
                    resolve({ success: selectedAnswer === currentDefinition.correctDefinition, term: selectedAnswer });
                } else {
                    // 用户输入无效数字或非数字内容
                    resolve({ success: false, term: userAnswer });
                }
            });
        });
    }

    let quitDrill = false;

    while (definitions.length > 0 && !quitDrill) {
        const randomIndex = Math.floor(Math.random() * definitions.length);
        const currentDefinition = definitions[randomIndex];

        const result = await drillTerm(currentDefinition);

        if (result.success) {
            score++;
            definitions.splice(randomIndex, 1);
            console.log("Correct\n");
        } else if (result.term === "q") {
            quitDrill = true;
        } else if (result.term === "timeout") {
            console.log("Please answer within 5 seconds");
        } else if (isNaN(result.term) || result.term > 3 || result.term < 0) {
            console.log("Please enter a number 1-4 or 'q' to quit the program");
        } else {
            console.log("Incorrect.");
        }
    }

    const statusMessage = quitDrill ? `Incomplete: User quit the drill. Score: ${score}/${defBegin}` : `Complete: Score - ${score}/${defBegin}`; 
    console.log(`${statusMessage}`);
}

已尝试的解决方法

  • 暂停和恢复readline
  • 将题目及选项的console.log移到Promise内部
    以上方法均未能解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 10:52:19