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';
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';
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.