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?
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
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!
Related
I am trying to make a cookie clicker game, and one item that you can get in shop is a bot where it adds x amount of credits to your current amount of credits every second. I want to be able to make multiple of these bots with variations, so not sure if setInterval would be usable in this case. How can I make this?
Note: The timer only starts when a variable is turned to false, so the timer shouldn't start when the app is opened.
P.S. I am using React
let bought = false
const [credits, setCredits] = useState
if (bought) {
For every second {
setCredits(credits+1)
}
}
I think you have to calculate seconds after each reaction on click,
you should use setInterval() in JavaScript function.
Example --
let time = document.getElementById("time");
function clock(){
let date = new Date();
let clocktime = (date.toString().split('G')[0]);
time.innerHTML = `${clocktime}`;
}
setInterval(clock, 1000);
First target an element then change its text to this function's output, and give time here in setInterval() function, for how many seconds you want to repeat that function (for how many seconds)
I am doing a simple math game in HTML and JavaScript for school, this is just a small part of it. Basically I have a button that I want to be able to press, and each time I press it I want it to output a new number to the innerText of a div in the HTML document.
Right now I get the random number, but I have to refresh the page to get a new one since it keeps outputting the same one if I press it again.
const mathQuestion = document.getElementById('math-question')
const newNumbers = document.getElementById('new-btn')
newNumbers.addEventListener('click', setQuestion)
function setQuestion () {
mathQuestion.innerText = calc.toString();
console.log(calc);
}
var calc = Math.floor(Math.random() * 100) + 1;
Yes, it's very simple and probably not the easiest or even the correct way to do it, but I am at a loss here.
I suspect I need to run another function for reseting the text or something after ive set the innerText, but I don't really know where to start.
Currently, you only generate the random number once and when you click the button, you set the same number in the HTML. That is why you see the same number irrespective of how many times you click the button.
Number changes on page reload because each time page reloads, new random number is generated.
You need to re-generate the random number every time the button is clicked. To do this, move the random number generation code inside the event handler function and it should work as expected.
function setQuestion () {
var calc = Math.floor(Math.random() * 100) + 1;
mathQuestion.innerText = calc;
}
Also, there's no need to explicitly convert the number into a string.
I am new to JavaScript.
I have been creating a game- which includes the number of goes a person has had to guess a random number.
I have created the button however I am having problems trying to restart the game - making a new random number to be generated and the number of goes to return to 0
var randomno =Math.floor(Math.random() * 100 ) + 1;
let restart = document.getElementById("restart");
function restartGame(){
num();
}
}
restartGame();
This is only a small snippet of my code.
You want to assign a click handler to your restart element which is missing from the OP code snippet... https://developer.mozilla.org/en-US/docs/Web/Events/click
document.getElementById("restart").addEventListener("click", function() {
// restart the game
});
A quick fix which may or not be optimal for you is to simply refresh the page. Use something like 'location.reload();' to do this.
As I could understand you only need to re-assign some variables.
To do that, just put the variable name followed by the equals sign and the new value you want it.
var randomno = Math.floor(Math.random() * 100 ) + 1;
randomno = Math.floor(Math.random() * 100 ) + 1;
The second line the variable is being re-assigned.
If you also have a problem of binding an action for your button to call a javascript event(in your case restart the game), please read this article: https://developer.mozilla.org/en-US/docs/Web/Events/click
im trying to make a script that picks 1 random class name out of 3
every 1 minute and clicks the button with the chosen class
so far i created the script that clicks on the button:
setTimeout(function () {
$(".btn-danger").trigger("click");
}, 100);
The problem is if i put it in a while(true)
the site stuck and then the browser crashes.
Also im have no idea how to make it to chose random class so i putted in one of them.
Will be glad to get some help here :D
Check out setInterval() to run something over and over. You can generate a random index from 0 to 2 with Math.floor(Math.random() * 3).
For example, you could select a random class name like this:
var classes = ["classA", "classB", "classC"];
function selectRandomArrayElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
var rand = selectRandomArrayElement(classes);
So, putting it all together:
var classes = ["classA", "classB", "classC"];
function selectRandomArrayElement(array) {
return array[Math.floor(Math.random() * array.length)];
}
// click on a the object with a random class name every minute
setInterval(function() {
var rand = selectRandomArrayElement(classes);
$("." + rand).trigger("click");
}, 1000*60);
In Javascript, you can't use while(true) long duration loops like this block the rest of the browser from processing events and thus your the click events you trigger are never processed. Instead, you use timers to do something repeatedly.
You're looking for setInterval instead of setTimeout, which will invoke the callback indefinitely at the interval you specify.
setInterval(function () {
$(".btn-danger").trigger("click");
}, 60000);
Should work for you. while(true) crashes your browser because you're creating an infinite loop that blocks any other code from executing.
setTimeout uses milliseconds and only occurs once. Use setInterval with one second * 60 to get a minute.
var minute = 1000 * 60;
setInterval(function() { $(".btn-danger").trigger("click");
}, minute);
I have a home made(not by me of course) program that runs in milliseconds and I'd literally have to put millions of milliseconds to get it to do what I want it to do, so I'm trying to change it to seconds, or even minutes... I know the var milli is what I should be changing but dunno if I change it to var sec or var secs or var seconds or what, I'm not very knowledgeable of coding so I'm sure this is a simple answer, and I've tried a few different things that did not work, so that's why I came here, thanks if you can answer :) ignore the fact that it's not properly formatted as code in this post
<script>
var a=0;
var milli;
function collect1()
{
var milli = document.getElementById("numbers").value;
var links=document.getElementById('linkholder').value;
links = links.replace(/[\n\r]/gi , " ");
var link=links.split(" ",100000);
var iframe1=document.getElementById('iframe1');
iframe1.onload = function(){setTimeout(collect1, milli);};
iframe1.src=link[a];
a++;
Change this line
var milli = document.getElementById("numbers").value;
to
var milli = document.getElementById("numbers").value * 1000;
1 second is 1000 milliseconds.
Also note that this variable milli is not the same as the var milli; on the third line. If you want to turn that variable into seconds you need to multiply it with 1000 too.
1 sec = 1000 milliseconds
The only place you are using the milli variable in the code you've provided is here:
iframe1.onload = function(){setTimeout(collect1, milli);};
so if you want the whatever the milli variable is to actually be how many seconds you want to wait then multiply it by 1000:
iframe1.onload = function(){setTimeout(collect1, milli*1000);};
Side note: That is going to wait a long time....
It is hard to guess, what your code is meant for, since I don't know what your html page looks like.
But since the variable milli is only used once (as a parameter to setTimeout), I would guess that you could change that line of code from:
iframe1.onload = function(){setTimeout(collect1, milli);};
to:
iframe1.onload = function(){setTimeout(collect1, milli * 1000);};
and see what is happening.