내 node.js 프로그램에서 foo
을 30 초마다 인쇄하도록합니다. 그래서 다음과 같은 코드를 작성합니다 :node.js 몇 초 동안 일시 중지
let count = 0
function foo() {
console.log(`foo`)
count += 1
// do other things that takes about 20 seconds.
}
while (count < 10) {
console.log(`inside while loop`) // my screen keep printing `inside while loop` until "JavaScript heap out of memory" error
setTimeout(foo, 30000) // It looks like that `foo` is scheduled to be triggered after 30 seconds. Before it gets triggered, node.js program keeps doing other things.
}
이 코드는 예상 한대로 작동하지 않습니다.
foo
은 30 초 후에 트리거 될 예정입니다. node.js 프로그램은 트리거되기 전에 다른 작업을 계속합니다.
어떻게 30 초 동안 프로그램을 일시 중지 할 수 있습니까?
프로그램이 몇 초 동안 실행되고 JavaScript heap out of memory
오류로 인해 충돌이 발생했습니다.
sleep module이 작동하지 않습니다. 잠들 때마다 foo
은 필요한 일을 그만 두었습니다. 루프 반복을 많이 만들고 setTimeout
콜백을 등록하는 동안
foo가 비동기이므로 while 루프가 해당 시간 초과보다 빠르게 반복되므로 메모리 힙이 발생합니다 –