let x = "value before setTimeout";
function cb() {
console.log(currentValue);
}
setTimeout(cb, 3000);
x = "updated value";
How to print "value before setTimoeout" with the help of callback function. How to capture the old value and use it?
3
Answers
Store it as a temporary coefficient:
You can wrap your callback function inside another one that will keep the
currentValue
in its closure so you can access it later.The main difference is that your callback function has to be called once now (
cb(x)
) in order to bind that value.By passing x as an argument to the callback function, you can capture its value at the time setTimeout is set, before it gets updated. And then print that captured value inside the callback.