Looping setTimeout

Asked
Active3 hr before
Viewed126 times

9 Answers

settimeoutlooping
90%

Factor out the setTimeout function and invoke it immediately in the for loop.,setTimeout function in JavaScript usually takes a callback function as an argument. A callback function is a function that is executed after another function finishes running. In this case, it will run after for loop finishes. At this point, i is already 5 when the console.log([i]) is about to be executed. Due to the closure of JavaScript, the console.log has access to the i =5 which is defined as an outer layer of the setTimeout. Thus, when the console.log is executed, it logs undefined(array[5] = undefined) five times.,The reason being is that for loop only exits until the set condition breaks. For the above for loop, it will exit once i = 5. Therefore, i equals 5 when the for loop exits.,When you see the above code snippet, what do you expect the console.log(array[i]) will print? 1, 2, 3, 4, 5 respectively? If you think so, that’s wrong! The answer is undefined * 5. Why would it log undefined, 5 times?

var array = [1, 2, 3, 4, 5]
for (var i = 0; i < array.length; i++) {
   setTimeout(() => {
      console.log(array[i])
   }, 1000);
}
load more v
88%

You can create a setTimeout loop using recursion:,I’ve read online that setTimeout is more accurate, and you can have setTimeout loops somehow. However, I have not found a generic version that illustrates how this is possible.,This three functions are necessary because vars in the second function will be overwritten with default value each time. When the program pointer reach the setTimeout one step is already calculated. Then just the screen needs a little time. ,Could someone just show me a basic example of using setTimeout to loop something indefinitely? Alternatively, if there is a way to achieve more synchronous results with setInterval or even another function, please let me know.

You can create a setTimeout loop using recursion:

function timeout() {
   setTimeout(function() {
      // Do Something Here
      // Then recall the parent function to
      // create a recursive loop.
      timeout();
   }, 1000);
}
load more v
72%

Set the timeout from within a function,There isn't a cross-browser way of passing a timeout callback with arguments. Only modern browsers support the following syntax:,for (let i = 1; i <= 5; ++i) { setTimeout(function(){ console.log(i); }, 1000); } let will create block level scope and it will work fine.,setTimeout is a great tool in JavaScript, but it has its drawbacks and problems you should be aware of:

There isn't a cross-browser way of passing a timeout callback with arguments. Only modern browsers support the following syntax:

setTimeout(myFunction, 1000, myVariable);

There are workarounds that look like this:

setTimeout(function() {
   myFunction(myVariable);
}, 1000);

The variables you're passing in don't keep their initial values, so if you're changing them (as in a for loop) please be aware:

for (i = 1; i <= 5; ++i) {
   setTimeout(function() {
      console.log(i);
   }, 1000);
}

Set the timeout from within a function

for (i = 1; i <= 5; ++i) {
   setDelay(i);
}

function setDelay(i) {
   setTimeout(function() {
      console.log(i);
   }, 1000);
}
load more v
65%

Every time we loop, setTimeout() is passed outside of the call stack and enters the event loop. Because of this, the engine is able to move to the next piece of code. The next piece of code happens to be the remaining iterations of the loop, followed by console.log(‘The loop is done!’).,When the browser encounters doSomething() it gets placed in the call stack:,At this point, the loop is over, our setTimeout() functions are still counting down, and all that remains in the call stack is console.log(‘The loop is done!’).,Finally, the console.log() statement can get passed into the call stack to be executed:

What does this code output?

for (var i = 1; i < 6; i++) {
   setTimeout(function() {
      console.log(i);
   }, 1000);
}
console.log('The loop is done!');
load more v
75%

function timeout() {
   setTimeout(function() {
      // Do Something Here
      // Then recall the parent function to
      // create a recursive loop.
      timeout();
   }, 1000);
}
load more v
40%

As shown in the above piece of code, the callback function is executed after the specified time interval expires.,Now let’s see how a setTimeout executes inside a JavaScript for loop. Here is how the code looks:,The above code when executed will print the following output in the browser console.,Let’s try to understand what is really happening in the above piece of code. The setTimeout function callback isn’t triggered until the for loop execution has completed. When the for loop has finished executing the value of i is 5. Now when the setTimeout call begins to execute it uses the last set value of i which is 5. Hence 5 is printed in all the setTimeout callbacks.

// setTimeout example 
setTimeout(function() {
   console.log('setTimeout fired afer 3 seconds');
}, 3000);
load more v
22%

A JavaScript runtime uses a message queue, which is a list of messages to be processed. Each message has an associated function which gets called in order to handle the message.,Basically, the setTimeout needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your setTimeout., Functions The arguments objectArrow function expressionsDefault parametersgetterMethod definitionsRest parameterssetter ,When bar calls foo, a second frame is created and pushed on top of the first one, containing references to foo's arguments and local variables.

function foo(b) {
   let a = 10
   return a + b + 11
}

function bar(x) {
   let y = 3
   return foo(x * y)
}

const baz = bar(7) // assigns 42 to baz
load more v
60%

setTimeout(function, milliseconds)Executes a function, after waiting a specified number of milliseconds.,setInterval(function, milliseconds)Same as setTimeout(), but repeats the execution of the function continuously.,The second parameter indicates the number of milliseconds before execution. ,The clearTimeout() method stops the execution of the function specified in setTimeout().

Timing Events

The window object allows execution of code at specified time intervals.

window
load more v
48%

setTimeout allows us to run a function once after the interval of time.,setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.,All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.,For setInterval the function stays in memory until clearInterval is called.

let timerId = setTimeout(func | code, [delay], [arg1], [arg2], ...)
load more v