为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

肥皂起泡泡 2022-01-13 15:42:04
我希望您就我创建的一个功能寻求帮助,该功能允许刷新列表中的频道,但我有一个问题,每 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)}
查看完整描述

2 回答

?
守着一只汪

TA贡献1872条经验 获得超4个赞

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


尝试不递归地编写它:


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以便调用者可以存储它并在以后需要时清除它。


查看完整回答
反对 回复 2022-01-13
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

不要以这种方式使用 setInterval。使用设置超时。通过调用 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);

}


查看完整回答
反对 回复 2022-01-13
  • 2 回答
  • 0 关注
  • 195 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号