0

I have been trying to create a function that generates a random number but I want this number to change every 5 minutes. Below is the code that I have tried:

function randNum(){
    let randomNumber = Math.floor(Math.random() * 10);
    const paragraphNew = document.createElement("p");
    const watchNow = document.createTextNode(randomNumber + " are viewing this product now.");
    paragraphNew.appendChild(watchNow);
    const element1 = document.getElementById("cart-container");
    element1.appendChild(paragraphNew);
}

When I try using the setInterval function like this:

let randomNumber = setInterval(Math.floor(Math.random() * 10), 5000);

I always get 1 as a result. I have also tried calling the function like this:

setInterval(randNum, 5000);

The problem is that a new paragraph is getting added everytime, without deleting the last one.

How can I make it work so I can generate the same number that lasts 5 minutes even after I refresh the page?

  • look at this [answer](https://stackoverflow.com/a/47593316/3462319). Write your own PRNG and then you can give it your own seed which can be based on the time – depperm Jun 24 '21 at 15:40
  • try this `let randomNumber = Math.floor(Math.random() * 10); setInterval(randomNumber = Math.floor(Math.random() * 10), 5000);` – AlTheLazyMonkey Jun 24 '21 at 15:42

2 Answers2

3

Ok) so basically when you refresh your page, all the variables and timeouts are reset. What comes to mind - you can store the variable in some sort of storage (ex. - localeStorage) along with creation date, then run your func with timeout like you did, but if you reload the page - look at storage first, and compare datestamp with current date)

Also keep in mind the things @Josh mintioned in his answer

Nikita Mazur
  • 1,602
  • 1
  • 5
  • 14
1

You're returning the interval instead of the value it generates. Try something like this:

let randomNumber = 0;

setInterval(() => {
  randomNumber = Math.floor(Math.random() * 10)
}, 5000);

alert(randomNumber)

Now you're updating the random number every 5 minutes. If you want to display the number every 5 minutes, add your log inside the arrow function. Let me know if you have anymore questions!

I missed the refresh the page part of your question. As @Nikita Mazur mentioned, local storage is the best way!

Josh
  • 718
  • 10
  • 25