-2

I want to generate a timestamp for each item inside the for loop but i am getting only one timestamp inside the loop.How can i make new timestamp for each item in the for loop in javascript.

for (var i = 0 ; i < 5; i++ ) { vm.workers[i].id = (new Date()).getTime(); }

This one provides only one timestamp instead of 5 different timestamp can anyone tell me how to generate multiple timestamps inside the loop.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72

3 Answers3

7

All the ids are the same because the loop takes no time at all to run. So how can you generate a unique number for each? Add one each time you use it.

var ts = (new Date()).getTime();
for (var i = 0 ; i < 5; i++ ) { 
  vm.workers[i].id = ts++
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
2

Answering the original question which had this loop:

for (var i = 0 ; i < 5; i++ ) { new Date().getTime(); }

You're not doing anything with them so it will only print the last one or none at all if you're not using the console.

Try logging each one with console.log.

for (var i = 0 ; i < 5; i++ ) { console.log(new Date().getTime()); }

assign them to a an array and add them like so like so will give you an array of date/time stanmps:

var list = [];
for (var i = 0 ; i < 5; i++ ) { list.push(new Date().getTime()); }
console.log(list);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • please try your code in you browser first; at least with a computer manufactured after 2010 :) – InQβ Dec 04 '17 at 14:12
  • @no1xsyzy It seems to work in chrome dev tools https://i.imgur.com/u21dRat.png :) – DeadEnglish Dec 04 '17 at 14:15
  • that is just by accident; the loop ran from one millisecond to next one, which not *must* but *may* produce different timestamps, and in this best result, it still produces only two timestamps – InQβ Dec 04 '17 at 14:19
  • @no1xsyzy, Not really. It's pushing to the array every loop so a new timestamp is generated (even though it is identical). When I answered, OP didn't specify they needed to be distinct timestamps, just that there needed to be 5 instead of 1. – DeadEnglish Dec 04 '17 at 14:27
  • That makes sense now; not noticed the time. – InQβ Dec 04 '17 at 14:42
0

A simple loop iteration can certainly take less than a millisecond to complete, hence you're getting the same timestamp.

Find a more reliable way to create id's such as a GUID.

Here's a function, taken from this S.O answer that creates GUID's:

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

console.log(guid())
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167