Print unique timestamps on a for loop

If you try to print the timestamp on a for loop, probably you'll get repeated results as the computer performs the operations in less than 1 ms.

Example:

javascript
for(let i = 0; i < 1000; i ++){
    console.log(Date.now())
}

/* The printed timestamp repeats itself several times
6 1633102772083
25 1633102772084
25 1633102772085
28 1633102772086
13 1633102772087
28 1633102772088
...
*/

The trick to make the printed results unique is to append the index at the end.

Example:

javascript
for(let i = 0; i < 1000; i ++){
    console.log(`${Date.now()}${i}`)
}

/* The approach looks good for the first 10 numbers
16331035373630
16331035373631
16331035373632
16331035373633
16331035373634
16331035373635
16331035373636
16331035373637
16331035373638
16331035373639
163310353736310 |
163310353736311 |---- But, you have a problem from here on
163310353736312 |
...
*/

To solve the previous issue, you need to append some zeros at the beginning of the indexes.

Example:

javascript
for(let i = 0; i < 1000; i ++){
    console.log(`${Date.now()}${i.toString().padStart(4, '0')}`)
    //                                         --
    //                                          index.toString().length is more generic
}

/* Now every number has equal lenght and they are sorted
16331039674280000
16331039674280001
16331039674280002
16331039674280003
16331039674280004
16331039674280005
16331039674280006
16331039674280007
16331039674280008
16331039674280009
16331039674280010
16331039674280011
16331039674280012
16331039674280013
*/

Bear in mind that you are adding some microsegonds (µs) to the real timestamp.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.