0

I'm new to programming and I have this little problem that needs solving. I want my code to be able to generate a random sequence of letters and numbers and I want it to generate a new sequence every day. I got it to the stage where it generates the random sequence but of course it's a new one everytime I refresh the page.

How do I go about keeping a random generated sequence for an entire day and have a new one the next day?

Edit: The daily sequence needs to be the same for every visitor!

This is what I have so far:

function randomSequence() {
   var sequence = "";
   var available = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

   for(var i = 0; i < 5; i++) {
       sequence += available.charAt(Math.floor(Math.random() * available.length));
   }

   return sequence;
}

var returned = randomSequence();

document.getElementById('sequence').innerHTML += returned;
  • If you're asking about storage options, you may want to start here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage – source.rar Jun 12 '14 at 12:27
  • Is you random key the same for every visitors of your page (ie ABCD... for everybody for day 1, EDFG for everybody on day 2...) or is it a code for each visitor (ie Visitor 1 has ABCD for day 1, Visitor has DEFG for day 2...) ? – Pierre Granger Jun 12 '14 at 12:29
  • What you're looking for is called "seeding" a random number generator. If you use the date as your seed, you'd get the same sequence of numbers throughout the day. Here's a question about a seedable random number generator in javascript: http://stackoverflow.com/questions/424292/seedable-javascript-random-number-generator – Sacho Jun 12 '14 at 12:30
  • @Pierre Granger: It's the same for every visitor. ABCD for everybody on day1 and a new one the next day. – signalrunner Jun 12 '14 at 12:30

1 Answers1

2

You need to persist your value. Client side, the best way of doing that with simple values is to use a cookie. This SO answer shows how to use cookies.

Taken from linked SO answer:

// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
Community
  • 1
  • 1
FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
  • This is turning out to be way above my knowledge level right now but I'll definitely look into this. Thank you very much for your answer. – signalrunner Jun 12 '14 at 12:56