Skip to content Skip to sidebar Skip to footer

Why Does Variable In Settimeout Callback Not Have Expected Value?

pic1pic2pic3

Solution 1:

You can't use the variable j directly in the setTimeout function because that function runs some time later after your for loop has completed and thus j has the terminating value, not the value when you called setTimeout.

You can capture the current value of j in a function closure that would be available in the setTimeout function like this:

for (var j = 0; j * pixelMovement < 600; j++){
    window.setTimeout(function(cntr) {
        returnfunction() {
            style.marginLeft = (marginLeft - cntr * pixelMovement) + "px";
        };
    } (j), 150);
}

I find this type of closure kind of confusing. I'll try to explain what's happening. We pass to the setTImeout() function the result of executing an anonymous function that takes one parameter (which I named cntr here) and we pass the value of j as the value of that parameter. When that function executes (which now has the value of j available inside it), that function returns another anonymous function. This other anonymous function is what setTimeout will actually call when it fires. But, this second anonymous function is inside a function closure from the first function that has the captured value of j in it (as a variable that I renamed cntr while inside the function closure to avoid confusion in explaining it). It's the anonymous functions that make it so confusing, but it works.

Solution 2:

It should be anything, because window.setTimeout is an "async" function so it returns immediately after executing.

So in your code the for loop keeps looping and after a while (150ms) your function is being executed and the j variable's actual value is printed out.

Solution 3:

The functions you create and pass to setTimeout are all referencing the same loop counter variable j - after the loop has run its course, j will be set at the value which caused the loop to terminate. You need to use a closure to ensure the functions you're creating in the inner loop have access to the value j had at the time the function was defined.

See this answer for more detail on the problem and the solution:

(Silly variable name to make it clear that it's distinct from j):

window.setTimeout((function(jWhenFunctionWasDefined) {
  returnfunction() {
    style.marginLeft = (marginLeft - jWhenFunctionWasDefined * pixelMovement) + "px";
  }
})(j), 150)

Post a Comment for "Why Does Variable In Settimeout Callback Not Have Expected Value?"