Vaibhav Chiruguri
Vaibhav Chiruguri

Reputation: 197

javascript setTimeout() outputs save as variables

I want to save setTimeout() outputs as variables.

for example:

function time() {
 return  (new Date).getTime();
 }

for (var x=0; x<10; x++) {
   setTimeout( time() , 2000);
}

the above javascript code returns time in milliseconds every 2 seconds upto 10 times.

So we'll get 10 outputs. I want to save those outputs as 10 variables. So i'll be able to calculate average etc.

Please any help will be appreciated.

Upvotes: 0

Views: 1841

Answers (2)

Mulan
Mulan

Reputation: 135237

An alternative loop could be

EDIT: based on one of your comments, this script now outputs the average, too

var times = [];

var calculateAverage = function() {
  var sum = times.reduce(function(sum, t) { return sum += t; }, 0);
  console.log("Average:", sum/times.length);
};

var timer = setInterval(function() {
  times.push((new Date).getTime());
  if (times.length === 10) {
    clearTimeout(timer);
    calculateAverage();
  }
}, 2000);

Output

Average: 1376671898024

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074485

the above javascript code returns time in milliseconds every 2 seconds upto 10 times.

No, it doesn't. It calls time immediately and passes its return value into setTimeout (which won't do anything with it), because you have the () after time. If you had setTimeout(time, 2000), it would schedule 10 calls to time, but all of them would occur roughly 2 seconds later (not every two seconds).

So we'll get 10 outputs. I want to save those outputs as 10 variables

This is what arrays are for. :-)

var times = [];

function time() {
    times.push((new Date).getTime());
    if (times.length < 10) {
        setTimeout(time, 2000);
    }
}

setTimeout(time, 2000);

Or if for some reason you can't modify time directly:

var times = [];

function time() {
    return (new Date).getTime();
}

function nextTime() {
    times.push(time());
    if (times.length < 10) {
        setTimeout(nextTime, 2000);
    }
}

setTimeout(nextTime, 2000);

Upvotes: 9

Related Questions