I'm very new to code so I might not understand some answers.
I'm having trouble turning a variable into a random number between 1 and 10 in this code.
<script type="text/javascript">
var money = 0
function Random() {
money = Math.floor((Math.random() * 10) + 1);
}
</script>
I've read that I need to put return followed by the randomizing code somewhere but I just don't understand where I place that on how I use it.
function Random() {
return Math.floor((Math.random() * 10) + 1);
}
function getRandom() {
var money = Random();
console.log(money);
document.getElementById("demo").innerHTML = money;
}
<button onclick="getRandom()">Click for random number</button>
<p id="demo"></p>
This line will work:
var money = Math.floor((Math.random() * 10) + 1);
But if you want to use a function, you can write it:
var money;
function Random() {
return Math.floor((Math.random() * 10) + 1);
}
// Re-usable anytime you want
money = Random();
Related
I have a default number and after the page loads, after each second, I have to add to it a number from this range: (0.02 - 0.006).
Here is the code:
var amount = 44522.1234;
setTimeout(start, 1000);
var i = Math.floor(Math.random() * (0.02 - 0.006) + 0.006);
console.log("initial" + i);
var num = document.getElementById('total');
function start() {
setInterval(increase, 1000);
}
function increase() {
if (i < amount) {
i++;
console.log(i);
num.innerText = amount + i;
}
}
<div id="total"></div>
The above code only increments the amount by 1 each second, instead of by a number in the specified range.
Math.floor will truncate the number, so it will never be in the range you want. Also, you should generate a new random number every second instead of incrementing the originally generated number.
var amount = 44522.1234;
setTimeout(start, 1000);
var num = document.getElementById('total');
function start() {
setInterval(increase, 1000);
}
function increase() {
var i = Math.random() * (0.02 - 0.006) + 0.006;
console.log("adding",i);
amount += i;
num.textContent = amount;
}
<div id="total"></div>
The first time I type the random variable in the console I get a number between 1 and 10 which is expected. Then every time I retype the random variable it gives me the same number. Why is this?
var random = Math.floor(Math.random() * 10) + 1;
Instead of using a variable, you should create a function to generate a random number.
const random = () => Math.floor(Math.random() * 10) + 1;
const number1 = random();
const number2 = random();
const number3 = random();
console.log(number1, number2, number3);
Also this is useful,
const randomVariable = function () {
return Math.floor(Math.random() * 4);
};
randomVariable();
I'am trying to make a simple calculation generator in prompt window. But it should not generate a negative number as answer, such as: x-y=-answer
My code so far:
CodepenLink
How it should look like
function myFunction() {
var randomNumber = Math.floor(Math.random() * 10);
var nxtRandomNumber = Math.floor(Math.random() * 10);
var question = prompt("What is:"+ randomNumber+ " minus " + nxtRandomNumber);
if(nxtRandomNumber > randomNumber){
return ;
}
var result = Number(randomNumber) - Number(nxtRandomNumber);
document.getElementById("demo").innerHTML = "Number:" + answer + " was right!";
}
<p>Push the button to start </p>
<button onclick="myFunction()">Calculate!</button>
<p id="demo"></p>
make sure when you calculate nxtRandomNumber to use the value of randomNumber as a minimum.
So if randomNumber is 5, nextRandomNumber should be calculated to compute a number at least equal to 'randomNumber'
for ex:
nextRandomNumber = Math.floor(Math.random() * 10) + randomNumber;
Theres a trick to generate random number between 2 values.
var nxtRandomNumber = Math.floor(Math.random() * (10 - randomNumber) + randomNumber);
From mdn
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.>>>
I am trying to set a variable random number of dots. I can generate random numbers using Math.random(). I tried this without any luck:
function generate() {
Math.floor(Math.random() * 500)
}
var randomdots = generate();
What is the correct approach to set a variable random number of dots?
This method does nothing useful, it throws away the result before using it. Maybe you want:
function generate() {
var count = Math.floor(Math.random() * 500);
var result = '';
for (i = 0; i < count; ++i) {
result = result + '.';
}
return result;
}
document.write(generate());
Remember that functions in JavaScript must have a return if you want to get a value from them.
You can also use this
function generate() {
var index = Math.floor(Math.random() * 500);
return new Array(index).join(".");
}
var randomdots = generate();
You could have a JavaScript that writes bullets on page load. Do it like this:
var number = Math.ceil((Math.random() * 500)) + 1;
for (i=0;i<number;i++){
document.getElementById('output').innerHTML += '• ';
}
<p id="output"></p>
Let me know if you need additional help!
Although caslaner's answer seems to be the easiest way to achieve this, for educational purposes, here's a recursive function that does the same.
function generate(str,rm) {
if(rm === undefined) rm = Math.floor(Math.random() * 500);
return rm ? generate((str||'') + '.',rm-1) : str;
}
document.write(generate());
How can I run this every few second , without blocking the rest of the pagefrom loading.
function Create() {
var SomeArray = [];
for ( var i=0; i<=1 ; i ++) {
SomeArray[i] = (Math.random() * 10) + 1;
//alert(arr[0]);
}
return SomeArray;
}
var x = Create();
alert(x[0] + x[1]);
I was trying this var timer = setInterval(Create, 5000); it prevent loading rest of the page.
i want to get new values every few seconds
A basic example would be:
var counter = 0;
var timerRef;
var increment = function() {
counter += 1;
console.log(counter);
timerRef = setTimeout(increment, 1000);
}
setTimeout(increment, 1000);
// clearTimeout(timerRef);
Please avoid document.write refer the screencast for further details.
setInterval() can be configured to repeatedly call any function you designate at whatever time interval you request. But, you can't retrieve a return value from that function. Instead, you need to process the results from within the callback that you pass to setInterval() or call some other function and pass the results you generate inside the callback. This is how asynchronous functions work in JavaScript. I've provided several examples below of your options:
If you just want to generate two random decimal values between 1 and 10 (inclusive) every 5 seconds, you can do that like this:
var interval = setInterval(function() {
var rand1 = (Math.random() * 10) + 1;
var rand2 = (Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you wanted the random values to be integers (which is more common), then you would do this:
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
// now insert code here to do something with the two random numbers
}, 5000);
If you want to call a function and pass it those two random numbers, you can do this:
function processRandoms(r1, r2) {
// code here to do something with the two random numbers
}
var interval = setInterval(function() {
var rand1 = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
processRandoms(rand1, rand2);
}, 5000);
You can then stop the recurring interval at any time with this:
clearInterval(interval);