我的函数有问题:更新不和谐 js 的频道



我希望您通过我创建的功能寻求帮助,该函数允许刷新列表中的频道,但我有一个问题,每 10 秒内存只会上升,永远不会清空自己。我正在寻找已经超过5个小时了,即使我认为这是一件愚蠢的事情,也提前感谢您的帮助(对不起翻译,我不是英语(

我的代码 :

updateChannel: async function(client, newList){
let a = setInterval(async ()=> {
for(let i = 0; i < newList.length; i++){
const message = await this.replace$Var(client, newList[i][1])
const channel = await client.channels.get(newList[i][0])
channel.setName(message).catch(err => {
console.log(`The channel with the id : ${newList[i][0]} was deleted, please restart the bot`)
newList.splice(i,1)
i-=1
})
}
clearInterval(a)
this.updateChannel(client, newList)
}, 10000)
}

不要以这种方式使用 setInterval。使用 setTimeout。通过调用 setInterval,您可以在每次调用函数时创建一个 UNIQUE 计时器。SetTimeout 将创建一个结束的计时器,然后创建一个新的计时器。

尝试这样的事情:

updateChannel: async function(client, newList){
for (let i = 0; i < newList.length; i++) {
const message = await this.replace$Var(client, newList[i][1])
const channel = await client.channels.get(newList[i][0])
channel.setName(message).catch(err => {
console.log(`The channel with the id : ${newList[i][0]} was deleted, please restart the bot`)
newList.splice(i, 1)
i -= 1
})
}
setTimeout(this.updateChannel , 100000, client, newList);
}

从你使用它的方式来看,你根本不需要递归,像这样不受控制的无限递归只会导致内存问题,因为节点会创建越来越多的堆栈帧并捕获变量。

尝试编写它而不带递归:

updateChannel: function(client, newList) {
return setInterval(async ()=> {
for(let i = 0; i < newList.length; i++) {
const message = await this.replace$Var(client, newList[i][1])
const channel = await client.channels.get(newList[i][0])
channel.setName(message).catch(err => {
console.log(`The channel with the id : ${newList[i][0]} was deleted, please restart the bot`)
newList.splice(i,1)
i-=1
})
}
}, 10000)
}

我返回setInterval的返回值,以便调用方可以存储它并在以后需要时清除它。

最新更新