Add random number at Random time intervals - javascript

The thing is I want to add random number to a variable which is initially 0 which has to happen after a random timeout until the variable reaches 100.
$scope.var1 = 0;
do{
$timeout(function(){
$scope.var1 += Math.floor(Math.random() * 100 +1);
},Math.floor(Math.random() * 100 +1));
console.log($scope.var1);
}while($scope.var1<100)
$scope.var1 always stays 0, hence it goes to an infinite loop;

You get inifinity loop since $timeout function, that you use, is async, but your loop is sync. You have to use recursion:
$scope.var1 = 0;
function recursiveTimeout(){
$timeout(function(){
if($scope.var1 < 100){
$scope.var1 += Math.floor(Math.random() * 10 + 1);
console.log($scope.var1);
recursiveTimeout()
}
}, Math.floor(Math.random() * 1000 + 1));
}
recursiveTimeout()
http://jsfiddle.net/dwypcx1f/3/

Math.random is a JS function, so it has to be Math.floor(Math.random() * 100 +1); instead of Math.floor(Math.random * 100 +1);
I didn't checked the rest of your code.
You start a new loop on every loop iteration. I am not sure about the correct AngularJS syntax since I prefer Angular2, but something like this should work...
$scope.var1 = 0;
var repeatFunc = function repeatFunc() {
var num = Math.floor(Math.random() * 100 +1);
$scope.var1 += num;
console.log("num: ", num);
if ($scope.var1 < 100)
$timeout(repeatFunc, num);
}
repeatFunc();

Related

how to spawn 1 to 3 objects randomly many times Javascript

I am trying to spawn 1 to 3 monsters randomly many times in Javascript, this is the code i have for now but this only makes it randomly spawn when i refresh and then it keeps spawning the same amount of monsters the whole time.
function spawnMonster(){
setInterval(function(){
for(var i = 0; i < randomMonster; i++){
monsterDiv.innerHTML += monsterPic;
outputDiv.innerHTML = "monstrene angriper.</br>" + outputDiv.innerHTML;
}
}, Math.floor(Math.random()* 3000) + 1000);
}
I'm assuming randomMonster is the random value between 1-3.
When the variable is set, it (obviously) doesn't change as you did describe.
Just make sure you calculate a new randomMonster -value inside the setInterval function:
function spawnMonster(){
setInterval(function(){
const randomMonster = Math.floor(Math.random() * 3) + 1;
for(var i = 0; i < randomMonster; i++){
monsterDiv.innerHTML += monsterPic;
outputDiv.innerHTML = "monstrene angriper.</br>" + outputDiv.innerHTML;
}
}, Math.floor(Math.random() * 3000) + 1000);
}

Create a random number multiple times in JS

I want to generate a random number in Javascript 6 times. I've got the random variable declared and properly functioning. I just need to replicate it six times without logging it six separate times.
const randRoll = Math.floor(Math.random() * 10) + 10;
How would I go about this?
The proper way of doing this is using for loop
let randomNumbers = [];
for(let i = 0; i < 6; i++) {
randomNumbers.push(Math.floor(Math.random() * 10) + 10);
}
You can also do something like this
let randomNumbers = new Array(6).fill(0).map((v) => Math.floor(Math.random() * 10) + 10);
To create a random number in Javascript, the math.random() function is used. JavaScript math.random() generates a random decimal value between 0 and 1.
const random_num = Math.floor(Math.random() * 10); console.log(random_num);
As you can see,In the above example, I used the Math.floor() function to round our random number up to become a random integer, used “* 10” to generate a number between “1” and “10”.
If you need generate a number ( 1 to 100 ) you can multiply generated number by 100 and so on “* maxNumberHer”.
Random Number Between Two Values
Math.floor(Math.random() * (max - min) + min)
Between 900 to 1000
const generateRandomNum = (min, max) => Math.floor(Math.random() * (max - min) + min) console.log(generateRandomNum(900, 1000))
about Repeat 6 times
You can use for loop
for (let i = 0; i < 6; i++) { console.log(generateRandomNum(900, 1000)); }

Addition of two random number, with a different setTimeout ( Code almost working )

I made a simple code to add two random numbers.
Number 1 is minimum 1000 and maximum 2000.
It changes every 10 seconds.
Number 2 is minimum 1 and maximum 5.
It changes much faster ( delay is random )
The point is to addition number 1 + number 2, and "refresh" the total everytime number 2 changed.
Thanks in advance :)
function bignumber() {
var bignumber = 1000 + Math.floor(Math.random() * 1000);
$('#bignumber').text(bignumber);
return bignumber;
setTimeout(Big, 2300);
}
bignumber()
function addition() {
var rand = Math.floor(Math.random() * (10 - 5 + 1) + 5);
var smallnumber = Math.floor(Math.random() * (5 - 1 + 1) + 1);
var result = ??How to place Number1 here?? + smallnumber;
$('#smallnumber').text(result);
setTimeout(myFunction, rand * 300);
}
addition()
You have to define var bignumber outside function scope and update its value on function one also read value in function two
var bignumber =0 ;
function bignumber() {
bignumber = 1000 + Math.floor(Math.random() * 1000);
......
function addition() {
....
var result = bignumber + smallnumber;
...`

return multiple numbers from the loop

I want to create a function that returns 50 random numbers out of 100. If I write console.log(getMines), it returns all fifty numbers. But if I want to actually use them, my loop returns only one number. What's the problem?
var getMines = function() {
for (count; count <= 100; count++) {
return "d" + (Math.floor(Math.random() * 50));
}
}
You can only return a single value from a function. So once you return your first number, the loop essentially ends.
Try this instead!
var getMines = function() {
var minesArray = [];
for (var count=0; count <= 100; count++) {
minesArray.push("d" + (Math.floor(Math.random() * 50)));
}
return minesArray;
}
This will return an array of all the numbers, which you can then iterate through to do what you need. You can sort the numbers, or sum them etc.
I feel I should point out that your code is returning 100 random numbers between 1 and 50, not 50 random numbers between 1 and 100. If thats what you want and you misspoke in the OP nbd, but if you want 50 random numbers between 1 and 100 change count to <= 50 and multiply Math.random() by 100 instead.
You need create a var and push randoms, like this
var getMines = function() {
var returnArray = [];
for (var count = 0; count <= 100; count++) {
returnArray.push("d" + (Math.floor(Math.random() * 50)));
}
return returnArray;
}
you can only return only once from a function, you can use an array or object, add all values to it and return it.
var getMines = function() {
var arr = [];
for (count; count <= 100; count++) {
arr.push("d" + (Math.floor(Math.random() * 50)));
}
return arr;
}
If I read you question right, you need 50 numbers with a random value out of 100.
You need to switch the numbers in the for loop and the factor for getting a random number and take a initial value of zero for the looping variable, as well as not return some value inside of the for loop.
var getMines = function() {
var count,
array = [];
for (count = 0; count < 50; count++) {
array.push("d" + (Math.floor(Math.random() * 100)));
}
return array;
}
console.log(getMines());
.as-console-wrapper { max-height: 100% !important; top: 0; }
That can also be done with some cool ES6 tricks:
const getMines = ()=> Array.from(
{length:50},
()=> "d" + Math.floor( Math.random() * 100 )
);
If you need any random 50 numbers between 1 and 100 (both inclusive, I have tweaked your version to following. See if that helps.
var getMines = function() {
var nums = [];
for (var count=1; count <= 50; count++) {
nums[count-1]=Math.floor(Math.random() * 100) + 1;
}
return nums;
}
console.log(getMines());

Howto run function every few seconds that has return values?

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);

Categories

Resources