Javascript: setTimeout, for loops, and callback functions - javascript

I'm working on this code puzzle from here
Here's what I have so far:
for (var i = 0; i < 1000; i += 100) {
waitFor(i, function then() {
console.log(i)
})
}
// this will run a callback function after waiting milliseconds
function waitFor(milliseconds, callback) {
setTimeout(callback.apply(), milliseconds)
}
This logs out 0 to 900, but it does it all at once, and then waits 900 milliseconds at the end (instead of waiting i milliseconds in between each console.log).
Can anyone help me understand this?

You have two different issues going on in your code:
Closures are causing the value 1000 to printed always instead of 100, 200 ... etc.
The timeouts you are using are too short, so the functions are executing rapidly in succession.
The first problem is hard to explain in a single answer but I will try to give you some insights, since the function that is printing the value of the variables to the console is defined inside the for loop, that function will always keep the value of i that was there when the loop ended, and in your situation this is 1000.
To solve this problem, you need something similar to what #thg435 referred to in his comment, something like this:
// this will run a callback function after waiting milliseconds
function waitFor(milliseconds, callback) {
setTimeout(callback, milliseconds);
}
function createFunction(i) {
return function() { console.log(i); };
}
for (var i = 0; i < 1000; i += 100) {
waitFor(i, createFunction(i));
}
The second problem is that the values for the timeout are actually the values that i take as it is looping which are 100, 200 ... etc which are all very small values less than a second, so when the for loop finishes, those functions will all be ready to executed so they will get executed immediately one after the other.
To solve this issue you need to use a bigger time gap by multiplying i by 10 for example, like the following:
waitFor(i*10, createFunction(i));
^^^^

First timer call will be happenned when loop will be finished. In this context i = 1000 due to JS uses reference not a value. To fix this situation you have to use closures.

Related

Display index of an array with a delay of 3 seconds

In the following code, I tried to keep timeout but it doesn't work. I am sending array and expecting array index with 3 sec delay.
function displayIndex(arr){ // array as input
for(var i=0;i<arr.length; i++){
SetTimeout(function(){
console.log(i); // always returns 4
},3000);
}
}
displayIndex([10,20,30,40])
update:
var arr = [10,20,30,40];
function displayIndex(arr){ // array as input
for(var i=0;i<arr.length; i++){
setTimeout(function () {
var currentI = i; //Store the current value of `i` in this closure
console.log(currentI);
}, 3000);
}
}
displayIndex(arr); // still prints all 4.
Also, tried
arr.forEach(function(curVal, index){
setTimeout(function(){
console.log(index);
},3000);
}); // prints 0 1 2 3 but I do not see 3 secs gap between each display, rather one 3 sec delay before everything got displayed.
Use this:
function displayIndex(arr){ // array as input
var i=0;
var current;
run=setInterval(function(){ // set function inside a variable to stop it later
if (i<arr.length) {
current=arr[i]; // Asign i as vector of arr and put in a variable 'current'
console.log(current);
i=i+1; // i increasing
} else {
clearInterval(run); // This function stops the setInterval when i>=arr.lentgh
}
},3000);
}
displayIndex([10,20,30,40]);
1st: If you use setTimeout or setInterval function inside a for that's a problem 'couse all this are loops ways (the first two are loops with time intervals). Aaand setTimeout just run code inside once.
Note: setInterval need a function to stop it clearInterval, so that's why i put an if inside.
2nd: You are not setting currentI or i like a vector of arr operator. When you run an array the format is: arr[currentI], for example.
Doubts?
SetTimeout should be setTimeout. It's case-sensitive.
You're setting 4 timeouts all at once. Since you're incrementing the value of i every loop, it's going to be 4 at the end of the loop.
I'm not really sure what you're trying to do, but perhaps you wanted this?
setTimeout(function () {
var currentI = i; //Store the current value of `i` in this closure
console.log(currentI);
}, 3000);
The reason why it's behaving unexpectedly:
Case 1: In the first snippet, setTimeout() is adding the functions to the Event Queue to be executed after main thread has no more code left to execute. The i variable was passed as reference and, so the last modified value gets printed on each call since, it was passed by reference.
Case 2: In this case, since you are passing 4 explicit references, the values are different but, the execution order will same ( I.e., synchronous and instantaneous).
Reason: setTimeout() function always pushes the function passed to the queue to be executed with the delay acting as a minimum guarantee that it will run with the delayed interval. However, if there is code in the queue before the function or, any other code in the main thread, the delay will be longer.
Workaround: If you do not to implement blocking behaviour in code, I would suggest using an analogue of process.hrtime() for browser ( there should be a timing method on the window object and, write a while loop that explicitly loops until a second has elapsed.
Suggestion: I am somewhat confused as to why you need such blocking in code?

setInterval("clock()",50) different from setInterval("clock",50)?

Running the code, the browser will display RangeError.
function hide() {
h -= step;
pp.style.height = h + "px";
setTimeout(hide(), 1);
}
The problem is this line:
setTimeout(hide(),1);
Rather than telling JavaScript to call hide() again in 1 millisecond you actually call it immediately and only pass it's return value to setTimeout(). This causes an infinite recursion, which in the end causes the stack overflow/error you're getting.
To fix this, you'll have to use either syntax from your question's title:
Pass the function name only rather than calling it (better here).
Pass a lambda function.
Or pass the call inside a string that will be evaluated (IMO should be avoided or replaced with a lambda expression).
However, in your specific scenario I'd suggest using set Timeout(), considering your code is reasonably simple to always finish in time:
// Start the while thing
var handle = setInterval(hide, 1);
// Actual function
function hide()
{
// Do stuff
// End condition
if (done)
clearInterval(handle);
}
This code doesn't terminate, so it creates infinite number of stacks which causes stack overflow.
Consider adding some termination logic, like:
if (h < 0) { return }
This terminates the execution of hide() function when h is less then 0.
I'm assuming h and step are some global vars.
Also you're calling hide immediately and passing the value to setTimeout.
Correct way to recursively call function with timeout will be to pass function as value to setTimeout function:
setTimeout(hide, 1)
which is equivalent to:
setTimeout(function() { hide() }, 1)

Javascript: Async nested function in other async function gives unexpected results

I have two asynchronous functions the one nested in the other like this:
//Async 1
document.addEventListener("click", function(event){
for (var i in event){
//Async 2
setTimeout(function(){
console.log(i);
}, 200*i);
}
});
What I want is to be able and print each entry(i) of the event object. The output on Firefox is however this:
MOZ_SOURCE_KEYBOARD
MOZ_SOURCE_KEYBOARD
MOZ_SOURCE_KEYBOARD
MOZ_SOURCE_KEYBOARD
..
If I move console.log(i) outside Async 2 then I get the correct result:
type
target
currentTarget
eventPhase
bubbles
cancelable
..
Why doesn't it work correctly when reading the i inside async 2? Shouldn't event be "alive" inside the whole Async 2 block of code as well?
setTimeout uses i as it appears in async1. That is, it references i instead of using the value of i when the timeout function is created. When your timeout function finally runs, it looks at the current value of i, which is the last key in event after the for-loop.
You can avoid this by using a self-calling function, such that the arguments of that function are local to the timeout function:
for (var i in event) {
setTimeout((function(i) {
return function() { console.log(i); }
})(i), 200 * i);
}
Use this:
document.addEventListener("click", function(event){
var count = 1;
for (var i in event){
//Async 2
setTimeout((function(i){
return function () {
console.log(i);
};
})(i), 200 * count++);
}
});
DEMO: http://jsfiddle.net/AQykp/
I'm not exactly sure what you were going for with 200*i, since i is a string (not even digits). But I tried to fix it with counter in my answer, assuming what you really wanted.
So the reason you were seeing the results you were was because of the common closure problem. The setTimeout callback will execute after the for loop completes, leaving i as the last key in event. In order to overcome that, you have to add a closure that captures the value of i at that point in the loop.
Event is indeed alive inside your callback.
The problem is that, by the time your function is executed, the value of i has changed (from what I can see from the output, the loop has ended and i has reached its maximum value) and thus outputting the same value for every callback.
If you use the function Ian commented, you will curry the actual value into a new function. That way the value of i can vary, you captured the current value inside the inner function

Is using setTimeout(fn, 0) to defer code execution until after the current call stack reliable?

I've got a function that is called an unknown number of times. I need to know how many times the function was run so I'm doing:
(function () {
var i = 0,
increment = function () {
if (i === 0) {
setTimeout(function () {
console.log('increment was called ' + i + ' times.'); // increment was called 3 times.
i = 0;
}, 0);
}
i++;
};
increment();
increment();
increment();
})();
Can anyone tell me whether this is reliable across all browsers or whether there's a better pattern to achieve this?
setTimeout() places a function on the queue, which is executed when all the other functions have been run.
If you call setTimeout() a few times before calling increment(), you will probably notice the i variable reaching a value greater than 1.
Yes this code snippet seems to be reliable across all browsers even in the lowest version of IE. I tried this in IE8 I works good.

Javascript setTimeout parameter reversing from loop

This loop is in a function and it counts down from 10, however if I alert the parameter passed using i in the setV function it actually counts up!
for (var i=10;i>0;i--){
setTimeout('setV('+i+',"Out")',100);
}
function setV(c,t){
alert(c);
}
All the setV are programmed to execute at the same time (100ms after the instaneous loop execution), the order isn't determined (see the spec).
You probably wanted
for (var i=10;i>0;i--){
setTimeout('setV('+i+',"Out")',100*(11-i));
}
If you are describing the behavior with:
setTimeout('setV('+i+',"Out")',i*100);
the reason it counts up is because a callback set for 1s will execute earlier than one set for 2s, which will execute earlier than one set for 3s...
When all of the timeouts are set to run at the same time, there is no promise what order they will run this.
This is a much better way to write that loop:
function initThis() {
var idx = 0;
function doOneIteration() {
window.alert(idx);
idx++;
if (idx <= 10) {
window.setTimeout(doOneIteration);
}
}
doOneIteration(); // Start loop
}
initThis(); // This makes it all happen

Categories