Random number loop program - javascript - javascript

I would like my program to return 10 random numbers but it isn't working it doesn't load the random numbers, I have linked the program to index.html so that's not the problem here, this is what I have tried:
function randomNumber(upper) {
return Math.floor(Math.random() * upper) + 1;
}
var counter = 0;
while (counter < 10) {
var randNum = randomNumber(6);
document.write(randNum + ' ');
counter += 1;
}

If it works in fiddle but not elsewhere it's most probably a problem with onload here as Doorknob already suggested.
function randomNumber(upper) {
return Math.floor( Math.random() * upper ) + 1;
}
window.onload = function () {
var counter = 0;
while (counter < 10) {
var randNum = randomNumber(6);
document.write(randNum + ' ');
counter += 1;
}
};
The bracketing with window.onload causes the code to wait until the whole page is loaded.

Related

How do I have multiple set timeouts running at once?

This is more of a question on how I should approach my problem, and not what code to use. this is the general framework/simplification of my code. I can provide the actual code if needed. question is below, it is similar to the last question I asked as it is part of the same system that isn't working:
for (i = 0; i < 10; i++) {
var amt = 0;
function checktime() {
console.log(amt + " / " + i);
amt++;
if (amt <= 5) {
setTimeout(checktime, 3000);
}
}
checktime();
}
I want it to have all the set timeouts running at once, for each i. the console results in
0 / 0
0 / 1
0 / 2
...
0 / 8
0 / 9
1 / 10
2 / 10
3 / 10
4 / 10
...
13 / 10
14 / 10
I'd like it to look like this:
0/0
0/1
0/2
0/3
...
0/9
1/0
1/1
...
5/9
5/10
sorry for the long question, but how would I go about doing this?
Have a function inside checktime that runs a loop. Set up your variables, and then pass the count variable into the inner function again with your setTimout.
function checktime() {
// Set the amt variable to zero
let amt = 0;
// Set count to zero if it doesn't exist
function loop(count = 0) {
// Log the new data
console.log(`${amt}/${count}`);
// Increase the count
++count;
// If count hits 10 reset the count
// and increase the amt variable
if (count === 10) {
count = 0;
++amt;
}
// Call the loop function again and pass in the new count
// as a parameter
setTimeout(loop, 1000, count);
}
loop();
}
checktime();
There are 2 ways you can do this.
Using nested loops like this
for(i = 0; i< 10; i++){
for(j = 0; j < 5; j++) {
console.log(i + " / " + j)
setTimeout(3000)
}
}
Using recursion like this:
function setTimeout_recurse(amt, i) {
if (amt < 5) {
console.log(i + " / " + amt)
amt ++;
setTimeout(3000)
setTimeout_recurse(amt, i)
}
}
for(i = 0; i< 10; i++){
var amt = 0;
setTimeout_recurse(amt, i);
}
You'll notice that the base is now i not amt which makes more sense to be the base.

Unlimited 6 sided dice roller

Need help with a JavaScript assignment from School but don't know how I should do it and was hoping for some tips?
We're supposed to create a 6 sided dice roller program and the user will have the option to choose between how many dices should be rolled, min 1 and max 5 dices.
The sum of the amount of dices used should always be displayed on the page. But if a number 6 is thrown, then this should make the program disregard it to the sum and instead throw two new dices, there should be an error message displaying this when it happens.
When all the dices are thrown the total sum of all the dices should be displayed and how many times you threw the dices.
I've managed to create this so far but I'm not sure how I should do regarding the number 6 or even if I'm on the right path here?
JS
function rollDice() {
var numDice = document.getElementById("diceNum").value;
var container = document.getElementById("dieContainer");
container.innerHTML = "";
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
};
var x, text;
x = document.getElementById("diceNum").value;
if (isNaN(x) || x < 1 || x > 5) {
window.alert('Input not valid');
document.getElementById("dieContainer").style.display = "none";
} else {
document.getElementById("dieContainer").style.display = "block";
}
};
EDIT
I updated it to this now
let diceThrows = numDice;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
console.log("You got a 6 och two new dices were thrown");
document.getElementById("msg").innerHTML = "You got a 6 och two new dices were thrown";
} else {
sum += diceRoll;
console.log(sum);
document.getElementById("msg").innerHTML = "Result: " + sum;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}
I managed to display the results, but wondering now if there is a way display the results without them getting reset every time you use the function?
Replace loop for by loop while:
let diceThrows = 6;
let sum = 0;
while(diceThrows > 0) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
if(diceRoll == 6) {
diceThrows += 2;
} else {
sum += diceRoll;
}
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
diceThrows -= 1;
}
You can do something like this:
function rollDice() {
var numDice = Number(document.getElementById("diceNum").value);
if (isNaN(numDice) || numDice < 1 || numDice > 5) {
window.alert('Input not valid');
return
}
var container = document.getElementById("dieContainer");
container.innerHTML = "";
var total = 0
for (var i = 0; i < numDice; i++) {
var diceRoll = Math.floor(Math.random() * 6) + 1;
container.innerHTML += '<div class="dice">' + diceRoll + '</div>';
if(diceRoll === 6) {
//Increase the maximum by 1 (because ignore 6: -1; add two: +2)
numDice++
//Decrease the current by 1 (to ignore the 6)
i--
continue
}
total += diceRoll
};
document.getElementById("diceTotal").innerText = total
document.getElementById("diceCount").innerText = numDice
}
<input type="number" id="diceNum">
<button onclick="rollDice()" >Roll Dice</button><br>
Total (without 6s): <span id="diceTotal" ></span><br>
Count of rolls (without 6s): <span id="diceCount" ></span><br>
<div id="dieContainer" ></div>

I can't get eval() to work with my javascript calculation

I am working on a javascript code which calculates the value of Pi. So here's the problem. When eval() calculates the string which is generated by the code it returns 1. It is supposed to return 1.49138888889 (which is a rough value of Pi^2/6).
Here's the code. It returns the correct calculation as a string, But eval() doesn't calculate it properly.
function calculate() {
var times = 10;
var functionpart1 = "1/";
var functionpart2 = "^2+";
var x;
for (var functionpistring = "", x = 1; times != 0; times--, x++) {
functionpistring = functionpistring + functionpart1 + x.toString() + functionpart2;
}
document.getElementById("value").innerHTML = eval(functionpistring.slice(0, functionpistring.length - 1));
}
function calculate() {
var times = 20, // max loops
x, // counter
f = 0, // value representation
s = ''; // string representation
function square(x) {
return x * x;
}
function inv(x) {
return 1 / x;
}
function squareS(x) {
return x + '²';
}
function invS(x) {
return '1 / ' + x;
}
for (x = 0; x < times; x++) {
f += square(inv(x));
s += (s.length ? ' + ' : '') + squareS(invS(x));
document.write(f + ' = ' + s);
}
}
calculate();

JavaScript setTimeout not working with prompt box

Here is my code:
var t = setTimeout("increment();", 1000 * 3);
var st;
function increment() {
st = 1;
}
for (i = 0; i < 10; i++) {
cnt = i;
var no1 = Math.floor(Math.random() * 101);
var no2 = Math.floor(Math.random() * 101);
if ((i % 4) == 0) {
crct_ans[i] = no1 + no2;
quest[i] = no1 + " + " + no2;
}
else if ((i % 4) == 1) {
crct_ans[i] = no1 - no2;
quest[i] = no1 + " - " + no2;
}
else if ((i % 4) == 2) {
crct_ans[i] = no1 * no2;
quest[i] = no1 + " x " + no2;
}
else if ((i % 4) == 3) {
crct_ans[i] = no1 / no2;
quest[i] = no1 + " / " + no2;
}
ans[i] = prompt(quest[i], "");
if (st == 1) break;
}​
I want to stop the for loop if 3 seconds pass. But this is not working. For loop runs after the 3 seconds also. How can I do this?
Remove () and quotes like this:
var t = setTimeout(increment, 3000);
Removing () disables running of that function straright away/immediately whereas setTimeout expects callabck.
Removing quotes makes sure that eval isn't used behind the scenes.
BTW, it is good practice to declare all variables with single var keyword like this:
var t = setTimeout(increment, 3000), st;
If it suits your requirements, you can simply check how much time pass.
Example:
var start = new Date();
for(i = 0; i < 10; i++){
var end = new Date();
var elapsed = end.getTime() - start.getTime();
if (elapsed >= 3000)
break;
}​
Try formatting like so:
var t = setTimeout(function(){increment();}, 3000);

Javascript Closure question

Why the following code prints "0 5 10 15 20 ... 100"?
(function () {
for ( var i = 100; i >= 0; i -= 5) {
(function() {
var pos = i;
setTimeout(function() {
console.log(" pos = " + pos);
}, (pos + 1)*10);
})();
}
})();
I declare pos = i , which should be in a descending order. This code originated from John Resig' fadeIn() function in his book Pro javascript techniques.
You're registering the timeouts in the correct order, the problem is they're timed in order of their value, so value 10 will be printed in 100ms, value 100 in 1000ms, etc.
So you need to change the timing calculation to subtract from the max value (in this case, 100)
(function () {
for ( var i = 100; i >= 0; i -= 5) {
(function() {
var pos = i;
setTimeout(function() {
console.log(" pos = " + pos);
}, (100 - pos + 1)*10); // note the subtraction here
})();
}
})();

Categories

Resources