I want to add 60 things to localstorage. Inside the for loop I’m creating an object, converting it to a string and adding it to localstorage, with the time as a key.
function populate()
{
for(var i=0; i < 60; i++)
{
var newDate = new Date();
var card = {
'name': i,
'cost': i,
'type': i,
'text': i,
'power': i,
'toughness': i};
localStorage.setItem(newDate.getTime(), JSON.stringify(card));
}
}
Logic dictates this should happen 60 times. In practise it happens between about 2 and 20 times, and the values of i given to the object’s attributes vary greatly. Sometimes I get 2 with values of 11 and 59, sometimes I get 18 with numbers from 1 up to 59 or 60. This for loop does not iterate as many times as it should, but it doesn’t even do it in order, it seems to be random.
What is going on here?
You are running into issues with overlapping times and so the duplicates are not inserted. This will separate the duplicates. You may choose a different implementation or a GUID, which is up to your discretion.