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.
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.
Share Improve this question asked Aug 16, 2013 at 16:36 Vaibhav ChiruguriVaibhav Chiruguri 1973 silver badges14 bronze badges 2- use an array with the push method. – Richard Commented Aug 16, 2013 at 16:38
- 1 Your code doesn't do what you describe. But to answer your question, use a single Array instead of 10 variables. – user2437417 Commented Aug 16, 2013 at 16:38
2 Answers
Reset to default 9the 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);
An alternative loop could be
EDIT: based on one of your ments, 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744959183a4603385.html
评论列表(0条)