-4

So I am making a function that has to be delayed and I need the old value not the new one

test='old';

setTimeout( function(test) {alert(test)}, 1000,[test]);

test='new';
  • 4
    If you want to provide a solution to a problem, then please ask a proper question and provide your solution as proper answer. – Felix Kling Aug 04 '13 at 21:32
  • Regarding passing additional arguments to the timeout callback, see this paragraph in the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout): *"Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer. If you want to enable this functionality on that browser you must use a compatibility code (see the [Callback arguments](https://developer.mozilla.org/en-US/docs/Web/API/window.setTimeout#Callback_arguments) paragraph)."* – Felix Kling Aug 04 '13 at 21:35
  • possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Antti Haapala -- Слава Україні Aug 05 '13 at 06:19

1 Answers1

2

A general solution that does not depend on setTimeout's ability to pass arguments to the callback (which does not work in IE as explained in the MDN documentation), is to use an IIFE to create a new scope and capture the current value of the variable:

test='old';

(function(test) {
    setTimeout(function() {
        alert(test)
    }, 1000);
}(test));

test='new';

This works for any kind of callback. See also JavaScript closure inside loops – simple practical example.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143