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

Discord.JS加密交易确认轮询的Interval定时器无法停止问题求解

修复方案

问题根源

你的定时器无法停止的核心原因是clearInterval传入的oner参数没有正确拿到定时器ID:你给setInterval的回调函数定义了oner形参,但调用时没有传入该参数,导致oner为undefined,清除逻辑完全不生效。

修复方法

将setInterval的返回值(即定时器唯一ID)存入变量,交易确认成功时直接用该变量清除定时器即可,同时优化了原有嵌套的Promise写法为更易维护的async/await格式,修正后的完整代码如下:

const axios = require('axios');
const fetch = require('fetch')
const cheerio = require('cheerio');
const { clearInterval } = require("timers");
const { Client, MessageEmbed } = require('discord.js');
const client = new Client()
module.exports = {
    name: 'check',
    cooldown: 10,
    description: 't',
    async execute(msg) {
        if(!msg.member) return
        const args = msg.content.trim(1).split(/ +/g);
        // 校验交易ID参数是否存在
        if (!args[1]) return msg.channel.send(`请输入要查询的交易ID`).catch(console.log);
        
        async function getConfirmation(){
            return axios.get(`https://mempool.space/api/tx/${args[1]}`)
        }
        try {
            const response = await getConfirmation();
            if(response.data.status.confirmed === true) {
                return msg.lineReply(`This transaction has already reached 1 confirmation!`).catch(e=>console.log(e))
            } 
            msg.reply(`I will notify you when this transaction reaches 1 confirmation.`).catch(e=>console.log(e))
            // 存储定时器ID
            const checkInterval = setInterval(async () => { 
                try {
                    const res = await getConfirmation();
                    if(res.data.status.confirmed === true) {   
                        const embed = new MessageEmbed()
                        .setTitle(`<a:check:849801483389501510> Transaction Confirmed`)
                        .setDescription(`Transaction ID:\n${res.data.txid}`)
                        .setColor(`GREEN`)
                        .setURL(`https://mempool.space/tx/${args[1]}`)
                        msg.channel.send(`${msg.author}`)
                        // 用存储的ID清除定时器
                        clearInterval(checkInterval)
                        return msg.channel.send(embed).catch(console.log)
                    }
                } catch (err) {
                    console.log(err);
                    // 可选:API调用报错时也清除定时器,避免无限报错
                    // clearInterval(checkInterval);
                }
            }, 180000)
        } catch (error) {
            console.log(error)
            return msg.channel.send(`Error. Probably means you didn't input an actual Transaction ID!`).catch(console.log)
        }
    }
};

额外说明

如果需要在API调用连续报错时停止定时器,可以放开代码中错误捕获块里的clearInterval(checkInterval)注释,避免无限发起无效请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:00:01