Reputation: 43
My Discord bot is built using Discord.JS. I need to check whether or not a crypto transaction has reached 1 confirmation, so I have it set on an interval to check. This works, it checks using the coinbase API, and can fetch whether or not it's confirmed. The only issue is that the interval never stops, and it spams it infinitely, checking for confirmations.
Any suggestions on how I can get the interval to stop after reaching 1 confirmation?
const axios = require('axios');
const fetch = require('fetch')
const cheerio = require('cheerio');
const { clearInterval } = require("timers");
const client = new Discord.Client()
module.exports = {
name: 'check',
cooldown: 10,
description: 't',
async execute(msg) {
if(!msg.member) return
const args = msg.content.trim(1).split(/ +/g);
async function getConfirmation(){
return axios.get(`https://mempool.space/api/tx/${args[1]}`)
}
var confi = getConfirmation().then(function(response){
if(response.data.status.confirmed === true) {
return msg.lineReply(`This transaction has already reached 1 confirmation!`).catch(e=>console.log(e))
} else {
msg.reply(`I will notify you when this transaction reaches 1 confirmation.`).catch(e=>console.log(e))
setInterval(function(oner){
getConfirmation().then(function(response){
if(response.data.status.confirmed === true) {
const embed = new Discord.MessageEmbed()
.setTitle(`<a:check:849801483389501510> Transaction Confirmed`)
.setDescription(`Transaction ID:\n${response.data.txid}`)
.setColor(`GREEN`)
.setURL(`https://mempool.space/tx/${args[1]}`)
msg.channel.send(`${msg.author}`)
clearInterval(oner)
return msg.channel.send(embed).catch(error =>{
console.log(error)
})
}
}).catch(error =>{
return console.log(error)
})
}, 180000)
}
}).catch(error =>{
console.log(error)
return msg.channel.send(`Error. Probably means you didn't input an actual Transaction ID!`).catch(error =>{
console.log(error)
})
})
}
};
Upvotes: 0
Views: 351
Reputation: 3677
setInterval(fx,n)
creates an interval. If you want to stop it, use clearInterval(intervalID)
.
If you want to execute it just once, use setTimeout(fx, n)
.
When you generate an interval, the function setInterval()
returns an unique id.
For example:
let counter = 0;
const myInterval = setInterval(() => {
counter++;
if (counter == 10) {
clearInterval(myInterval)
}
}, 1000);
This will count up to 10 and then stops the interval.
Upvotes: 1