I am generating a random number on click in jQuery. At the end of this post, you can see the code that I am working with.
Is there a way where every time a new random number gets generated it gets added to the old one in a variable called totalRandomNumbers?
I want to do it for all three variables random, random_0, random_1.
$("#reset").click(function(){
var random = Math.floor(Math.random() * 12);
var random_0 = Math.floor(Math.random() * 12);
var random_1 = Math.floor(Math.random() * 12);
$("#push0").html(random);
$("#push1").html(random_0);
$("#push2").html(random_1);
$('input[name="hamPush"]').val($("#push0").html());
$('input[name="zikPush"]').val($("#push1").html());
$('input[name="musPush"]').val($("#push2").html());
})
At the start of your JavaScript, make a variable:
var totalRandomNumbers = 0;
And when you generate your random number, add it to the variable.
totalRandomNumbers += (code to generate random number)
var randomSum = 0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
};
function sumRandom() {
randomSum += getRandomInt(1, 100)
};
$('.genRandomButton').on('click', function() {
console.log(randomSum)
}
Just tried in browser console:
var _totalRandomNumbers = 0;
Object.defineProperty(window, "totalRandomNumbers", {
get: function() { return _totalRandomNumbers += Math.random(); }
});
console.log(totalRandomNumbers);
console.log(totalRandomNumbers);
and so on :-)
You can do anything in get accessor, store old values etc.
Related
I've encountered a problem that's driving me crazy for like 10 days now... Basically i have a function that fire (the handleText) and I want to wait the end of that function before running a second one (the handleBackground).
I've tried deferred and promises but I think I don't understand them well because I can't get it to work the way I want.
function handleText(){
//BLAST INIT
var blastedwords = $('.baselineHeader').blast({
delimiter: 'word',
});
//SHUFFLE ORDER IN ARRAY
blastedwords = shuffleAds( blastedwords);
function shuffleAds(arr){
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
//ADD CLASS TO SPAN CREATED WITH BLAST WITH A RANDOM DELAY
blastedwords.each(function(index) {
var min = 45, max = 100;
var delay = Math.floor(Math.random() * (max - min) + min);
var that = $(this);
var t = setTimeout(function() {
$(that).addClass("test");
}, delay * index);
});
}
function handleBackground(){
$('.baselineHeader').addClass('processed');
}
handleText();
handleBackground();
Right now, handleText start, and handleBackground (my second function that I want to run after the first one is finished) fire at the same time and doesn't wait for handleText to finish.
I want handleText to run and wait for the each loop to give class to every span created with blast.js before running handleBackground.
Can someone help me with this ?
Have a great day folks :)
I'd recommend setting up a global variable totalTime which you can use to add up the inidivual delays. That way you can use another setTimeout to call the function handleBackground() after totalTime has passed.
var totalTime = 0;
blastedwords.each(function(index) {
var min = 45,
max = 100;
var delay = Math.floor(Math.random() * (max - min) + min) * index;
totalTime += delay;
var that = $(this);
var t = setTimeout(function() {
$(that).addClass("test");
}, delay);
});
setTimeout(handleBackground, totalTime);
Define delay outside of your function and each iteration increase the delay so that the next one is a random amout of time after the last one.
var delay = 0;
blastedwords.each(function(index) {
var min = 45, max = 100;
delay += Math.floor(Math.random() * (max - min) + min);
var that = $(this);
var t = setTimeout(function() {
$(that).addClass("test");
}, delay * index);
});
I need to generate a random number on every web page load and store that number in a hidden form field (id="field10"). Following is my code but its wrong.
Quick help is highly appreciated.
<script type='text/javascript'>
function test(final){
var min = 1;
var max = 9999999999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
var timeNow = new Date().getTime();
var final = num+'_'+timeNow;
document.getElementById('field10').value=test(final);
}
window.onload = test;
</script>
Lot of issues. Will give a quicker solution:
function test() {
var min = 1;
var max = 9999999999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
var timeNow = new Date().getTime();
document.getElementById('field10').value = num + '_' + timeNow;
}
window.onload = test;
I just removed few lines, which are unnecessary. This will work well. A glimpse of what I have done:
Removed all the parameters.
Removed the final variable (might cause troubles sometimes).
Directly set the value to the element.
Beautified the code.
Snippet
function test() {
var min = 1;
var max = 9999999999;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
var timeNow = new Date().getTime();
document.getElementById('field10').value = num + '_' + timeNow;
}
window.onload = test;
setTimeout(function () {
console.log(document.getElementById('field10').value);
}, 500);
<input type="hidden" id="field10" />
As a best practice, always put your scripts just before your closing body tag. You will not need to do the window.onload thing if you follow this as the DOM will already be loaded by then. Though window.onload might be necessary in some cases.
function randomNumber() {
var min = 1;
var max = 9999999999;
return Math.floor(Math.random() * (max - min + 1)) + min;
}
document.getElementById('field10').value = randomNumber() + new Date().getTime();
<!-- add type="hidden", i omitted here so you can see the results -->
<input id="field10">
I am new to JavaScript, I have two roll functions for each roll of a frame. I am unable to get the values of each of those rolls into a frame function to call on and use. If someone could help this would be great! thanks in advance, My code is below.
var Bowling = function() {
var STARTING_TOTAL = 0;
ROLL_ONE = Math.floor(Math.random() * 11);
ROLL_TWO = Math.floor(Math.random() * 11);
this.score = STARTING_TOTAL;
var firstScore;
var secondScore;
var totalScore;
Bowling.prototype.firstRoll = function() {
firstScore = ROLL_ONE
return firstScore;
};
Bowling.prototype.secondRoll = function() {
secondScore = Math.floor(Math.random() * 11 - firstScore);
return secondScore;
};
Bowling.prototype.frameScore = function () {
totalScore = firstScore + secondScore
return totalScore;
};
};
I can only guess what you're trying to achieve. I refactored you code a little bit:
var Bowling = function () {
var STARTING_TOTAL = 0;
this.score = STARTING_TOTAL; // remains unused; did you mean "totalScore"?
this.firstScore = 0;
this.secondScore = 0;
};
Bowling.prototype.firstRoll = function () {
this.firstScore = Math.floor(Math.random() * 11);
return this.firstScore;
};
Bowling.prototype.secondRoll = function () {
this.secondScore = Math.floor(Math.random() * 11 - this.firstScore);
return this.secondScore;
};
Bowling.prototype.frameScore = function () {
this.totalScore = this.firstScore + this.secondScore
return this.totalScore;
};
// now use it like this:
var bowling = new Bowling();
console.log(bowling.firstRoll());
console.log(bowling.secondRoll());
console.log(bowling.frameScore());
In my approach however, firstScore and secondScore are public properties.
To address the question of why the second roll can be negative: as your code currently stands, if the second roll is smaller than the first roll, the result will be negative. If you want it so that if the first roll is 6, the second roll will be a number between 0 and 4, try something like:
function randomInt(maxNum) {
return Math.floor(Math.random() * maxNum)
}
var maxRoll = 11
var rollOne = randomInt(maxRoll)
var rollTwo = randomInt(maxRoll - rollOne)
console.log(rollOne)
console.log(rollTwo)
Press "Run Code Snippet" over and over again to see it work.
Changes I've made:
I made a function, randomInt that gives a random number from 0 to some max number. This saves you from needing to write the same code twice.
I created a variable maxRoll that keeps track of what the highest possible roll is.
I subtract maxRoll from the first roll to determine what the max number for the second roll should be (maxRoll - rollOne). That's then given to randomInt.
I'm trying to push a random number of bunnies into a canvas from 1~10 in Javascript.
However, the Math.random() method doesn't seem to be working. It just gives me one bunny. What am I doing wrong?
var field = [];
var randomNum = Math.floor(Math.random() * 10);
field.push(randomNum * new Bunny());
function Bunny() {
...
}
It won't give you any bunnies at all. randomNum * new Bunny() will be NaN1, because you're trying to multiply an object with a number.
If you want multiple bunnies, you have to create them, probably in a loop:
var field = [];
var randomNum = Math.floor(Math.random() * 10);
for (var n = 0; n < randomNum; ++n) { // Loop
field.push(new Bunny()); // creating and pushing
} // multiple bunnies
function Bunny() {
// ...
}
1 Or a number, if you've overridden valueOf on Bunny.prototype, which seems unlikely.
var field = [];
var randomNum = Math.floor(Math.random() * 10);
for (k=0; k<randomNum; k++)
{
field.push(new Bunny());
}
I have a "guess a random number" game, where my code generates a random number between 1 and 100, and you try and guess the number. I'd like to have a reset button that refreshes the game by changing the variable with the random number in it. This is the relevant code I have.
var comparedNumber = RandomNumber();
function RandomNumber(){
var randomNumber = Math.floor(Math.random() * 100) + 1;
return randomNumber;
};
refresh.onclick = function(){
genComparedNumber();
};
Function Random Number runs on page load, but I can't seem to get comparedNumber to change.
Same logic as #juvian's answer
var Game = {
comparedNumber : randomNumber(),
refreshNumber : function(){
this.comparedNumber = randomNumber();
alert(this.comparedNumber);
},
refreshButton : document.querySelector("#refresh-button")
}
function randomNumber(){
var randomNumber = Math.floor(Math.random() * 100) + 1;
return randomNumber;
}
Game.refreshButton.addEventListener("click",Game.refreshNumber,false);
<button id="refresh-button">Refresh</button>