我的功能有问题:discord js 的 updateChannel

我希望您就我创建的一个功能寻求帮助,该功能允许刷新列表中的频道,但我有一个问题,每 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)

}


肥皂起泡泡
浏览 197回答 2
2回答

守着一只汪

从您使用它的方式来看,您根本不需要递归,并且像这样未经检查的无限递归只会导致内存问题,因为节点会创建越来越多的堆栈帧并捕获变量。尝试不递归地编写它:updateChannel: function(client, newList) {&nbsp; &nbsp; return setInterval(async ()=> {&nbsp; &nbsp; &nbsp; &nbsp; for(let i = 0; i < newList.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const message = await this.replace$Var(client, newList[i][1])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const channel = await client.channels.get(newList[i][0])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; channel.setName(message).catch(err => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`The channel with the id : ${newList[i][0]} was deleted, please restart the bot`)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newList.splice(i,1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i-=1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, 10000)}我返回返回值,setInterval以便调用者可以存储它并在以后需要时清除它。

慕雪6442864

不要以这种方式使用 setInterval。使用设置超时。通过调用 setInterval,您可以在每次调用该函数时创建一个 UNIQUE 计时器。SetTimeout 将创建一个结束的计时器,然后创建一个新的计时器。尝试这样的事情:updateChannel: async function(client, newList){&nbsp; for (let i = 0; i < newList.length; i++) {&nbsp; &nbsp; const message = await this.replace$Var(client, newList[i][1])&nbsp; &nbsp; const channel = await client.channels.get(newList[i][0])&nbsp; &nbsp; channel.setName(message).catch(err => {&nbsp; &nbsp; &nbsp; console.log(`The channel with the id : ${newList[i][0]} was deleted, please restart the bot`)&nbsp; &nbsp; &nbsp; newList.splice(i, 1)&nbsp; &nbsp; &nbsp; i -= 1&nbsp; &nbsp; })&nbsp; }&nbsp; setTimeout(this.updateChannel , 100000, client, newList);}
打开App,查看更多内容
随时随地看视频慕课网APP