I was trying to create a loop in Chrome console with Javascript that executes the same function all the time. Instead it doesn't output anything and it actually just increases Chromes memory size until it crashes. Any advice on what's going wrong here?
while(true){
window.setTimeout(function (){
console.log("Hello");
}, 4000)}
You're creating an immense number of setTimeout
events, all of which are created immediately in rapid succession and scheduled to be invoked 4000 ms after their creation.
Seems like you're looking for .setInterval()
to perform a continuous invocation.
window.setInterval(function() {
console.log("Hello");
}, 4000);
To do it with setTimeout
, you'd still not use any kind of imperative loop. You'd have the callback set up another setTimeout
when it runs.
window.setTimeout(function f() {
console.log("Hello");
setTimeout(f, 4000);
}, 4000);
I gave the callback function the name f
so that it could be used for the next timer.
In general, you don't "pause" your script. You schedule things to be done at a later time, and allow code to continue running until then. That's why you had a problem. The scheduled timer didn't pause anything, so the loop just keep running at full speed.