Skip to content Skip to sidebar Skip to footer

Set Timeout Function Callback Static Variables

When using the following code: var x = 5; setTimeout(function() { console.log(x); }, 2500); x = 10; the output is 10, and I totally understand why. However, I would like the o

Solution 1:

Just addressing the top part of your question:

var x = 5;
(function(currentX) {
    setTimeout(function () {
                    console.log(currentX);
            }, 2500);
})(x);
x = 10;

will display 5.

EDIT: All of what Felix Kling said. Note that while we create a function at different levels, the end effect is the same - the important point is that a function exists, to introduce a new scope, with a new variable that is disconnected from the original x.

EDIT2: Guys, go upvote Felix's answer a bit more, even if I beat him originally by 10 seconds, his is by now definitely the better of the two answers, not fair he only has my upvote :D

Solution 2:

I didn't read everything in detail, but I guess you want to create a new scope to capture the current value of your variable. Functions create scope and an easy way to create and call a function is to use an IIFE:

var x = 5;
setTimeout((function(y) {
  // this function is executed immediately and passed the current value of `x` returnfunction () {
   // this is function that is passed to setTimeout// since every function is a closure, it has access to the IIFE parameter yconsole.log(y);
  };
}(x)), 2500);
x = 10;

See also: JavaScript closure inside loops – simple practical example

However, there is an even simpler option: You can bind a specific value to a parameter of a function using .bind:

setTimeout(function(y) {
    console.log(y);
}.bind(null, x), 2500);

.bind creates a new function and sets this and parameters to the specific values you pass to it.

Post a Comment for "Set Timeout Function Callback Static Variables"