Javascript 我的函数有问题:用于discord js的updateChannel
我希望您能就我创建的一个函数寻求帮助,该函数允许刷新列表中的频道,但我有一个问题,每10秒内存只会增加一次,而她从不清空自己。我已经找了5个多小时了,即使我认为这是一件愚蠢的事情,也要提前感谢你的帮助(对不起,我不是英国人) 我的代码:Javascript 我的函数有问题:用于discord js的updateChannel,javascript,discord,Javascript,Discord,我希望您能就我创建的一个函数寻求帮助,该函数允许刷新列表中的频道,但我有一个问题,每10秒内存只会增加一次,而她从不清空自己。我已经找了5个多小时了,即使我认为这是一件愚蠢的事情,也要提前感谢你的帮助(对不起,我不是英国人) 我的代码: updateChannel: async function(client, newList){ let a = setInterval(async ()=> { for(let i = 0; i < newList.lengt
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)
}
updateChannel:async函数(客户端,newList){
设a=setInterval(异步()=>{
for(设i=0;i{
log(`id为${newList[i][0]}的频道已被删除,请重新启动bot`)
新列表。拼接(i,1)
i-=1
})
}
净空间隔(a)
this.updateChannel(客户端,newList)
}, 10000)
}
不要以这种方式使用setInterval。使用setTimeout。通过调用setInterval,您可以在每次调用函数时创建一个唯一的计时器。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:async函数(客户端,newList){
for(设i=0;i{
log(`id为${newList[i][0]}的频道已被删除,请重新启动bot`)
新列表。拼接(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)
}
updateChannel:function(客户端,新列表){
返回setInterval(异步()=>{
for(设i=0;i{
log(`id为${newList[i][0]}的频道已被删除,请重新启动bot`)
新列表。拼接(i,1)
i-=1
})
}
}, 10000)
}
我返回
setInterval
的返回值,以便调用者可以存储它并在需要时清除它。为什么要设置interval然后清除interval?除了使用setTimeout
?通常,clearInterval的操作会删除缓存,但显然不起作用。请尝试将代码更改为使用setTimeout
,然后查看您是否面临相同的问题。我想做与setinterval相同的操作,但每次都会删除缓存,因为ram只会上升,我已经尝试过settimeout,但它是相同的setInterval
或settimeout
不会修复每次创建新堆栈帧和变量副本的递归。这里甚至没有使用递归的理由,只要有一个setInterval来处理它而不破坏它本身,并且不递归就行了。这样更糟是什么意思?20秒内100毫:/n不,是这样的:/n我的内存再次增长:/n您能分享调用此函数的代码吗?设置单个间隔不太可能导致那么多内存泄漏。还请确认删除/不调用此函数可以解决内存问题。它甚至可能是this.replace$Var()
。我们实际上没有足够的信息,因为这段代码本身并不构成内存泄漏。