skip to Main Content
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


  1. Store it as a temporary coefficient:

    let a = 20
    
    function log(a) {
      console.log('a is: ' + a)
    }
    
    setTimeout(log, 1000, a)
    
    a = 43
    Login or Signup to reply.
  2. 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.

    let x = "value before setTimeout";
    
    function cb(currentValue) {
      return function() {
        console.log(currentValue);
        console.log(x);
      }
    }
    
    setTimeout(cb(x), 3000);
    
    x = "updated value";
    Login or Signup to reply.
  3. let x = "value before setTimeout";
    
    function cb(val) {
      console.log(val);
    }
    
    setTimeout(cb, 3000, x);
    
    x = "updated 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search