Home > Net >  return first value from setTimeout function
return first value from setTimeout function

Time:11-16

I have a large setTimeout function that generates dynamic variable that change every second. With other functions that I have, I want to attain a variable at the time that I call the setTimeout function, because I want to use it for another function that isn't contained within it. So essentially, I want the first value that I call and I don't want to disturb the function from running.

How would I go about in doing this?

Basically:

function schedule() {
<<changingvalue is here>>
setTimeout(function () { schedule() }, 1000);
}

console.log(<<changingvalue at a particular instance>>);

CodePudding user response:

You can use a promise to return the value after the first setTimeout finishes

let a = 1234;

function schedule() {
    a;
  return new Promise(r => setTimeout(function () { schedule(); r(a); }, 1000));
}

(async () => {
  console.log(await schedule());
})();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

or simply return the value

let a = 1234;

function schedule() {
    a;
  setTimeout(function () { schedule(); }, 1000);
  return a;
}

console.log(schedule());
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could use a class. Initialise the count in the constructor then call the loop method which updates the count, and then calls itself again once a second.

You can then create a new instance from the class and then call getCount from your other functions whenever you need to.

In this example I have an interval that calls the getCount once every three seconds, so you'll see output: 3, 6, 9 etc.

class Timeout {

  constructor() {
    this.count = 0;
    this.loop();
  }
  
  getCount() {
    return this.count;
  }
  
  loop() {
    this.count = this.count   1;
    setTimeout(this.loop.bind(this), 1000);
  }

}

const timeout = new Timeout();

setInterval(() => {
  console.log(timeout.getCount());
}, 3000);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related