我们显然在我们的代码中做了一些错误的事情,但我们似乎不能理解是什么。如果我们想在一个特定的时间间隔内获取一个文件,为什么我们不能使用这个代码呢?
<html>
<head>
<script>
let interval = 2
function fetchSource(source) {
fetch(source, { cache: 'no-cache' })
.then(response => {
console.log('Memory-bloating')
})
}
function test() {
fetchSource('https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg')
}
setInterval(test, interval * 1000)
</script>
</head>
<body>
Memory-bloating in chrome
</body>
</html>这里的问题是,每次我们获取数据时,我们的内存都随着图像的大小而增加,而且似乎从来没有被垃圾回收过。当网站运行了大约2-3个小时后,我们已经在电脑上填满了这张图片。
我们应该如何构建这个函数才不会有如此巨大的内存泄漏?
发布于 2018-10-04 21:02:24
尝试此代码,这将停止:
let interval = 2
let handle = ""
let still_fetching = false
function fetchSource(source) {
fetch(source, { cache: 'no-cache' })
.then(response => {
console.log('Memory-bloating')
clearInterval(handle)
still_fetching = false
handle = null
handle = setInterval(test, interval * 1000)
})
}
function test() {
if(still_fetching){
return;
}
still_fetching = true;
fetchSource('https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg')
}
handle = setInterval(test, interval * 1000)发布于 2018-10-04 21:36:41
在这里发帖,因为代码太长了,无法进行评论。我认为这可能是一个Chrome错误,但通过阻止并发下载,您可能能够确认这一点。
下面是与@McBern的代码等效的更简洁的代码,它删除了循环依赖,并且不需要维护额外的状态:
let interval = 2
function fetchSource(source) {
return fetch(source, { cache: 'no-cache' }) // NB: return
.then(response => {
console.log('Memory-bloating')
})
}
}
(function test() {
let url = 'https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg';
fetchSource(url).then(() => setTimeout(test, interval * 1000));
})();https://stackoverflow.com/questions/52647183
复制相似问题