So I'm trying to make this coin flip but it keeps flipping forever... when I want it to stop after 10 times. I also need a counter variable that tells me how many times it is flipped.
var coin = randomNumber (0,1);
write (coin);
while (coin < 10) {
coin = randomNumber (0,1);
write (coin);
}
The easiest way is to just use a for loop.
for (var i = 0; i < 10; i++) {
var coin = randomNumber (0, 1);
write (coin);
}
See this for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
If you want to stick to the while loop:
var timesFlipped = 0;
while (timesFlipped < 10) {
var coin = randomNumber (0, 1);
write (coin);
timesFlipped = timesFlipped + 1; // alternatively: timesFlipped++;
}
You haven't shown us your randomNumber function, but it's likely that it only produces numbers that are less than 10. Since your while loop says to keep going as long as coin is less than 10, the loop goes forever.
while loops are notorious for resulting in infinite loops. I personally never use them. Since you know how many times you need to loop, a counting loop is the correct choice.
Here's what you need:
// Write the function that gets random number and report the results a certain number of times:
function coinToss(numTimes) {
// Instead of a while loop, use a counting loop that will
// have a definite end point
for(var i = 0; i < numTimes; i++){
// Get a random number from 0 to 1
var coin = Math.floor(Math.random() * 10);
// Test to see if it is even or odd by checking to see if
// it is divisible by 2 with no remainder.
var even = (coin % 2 === 0);
// Report the results
console.log("The coin was " + (even ? "heads " : " tails"));
}
}
// Now, call the function and tell it how many times to loop
coinToss(10);
Related
I have four different button effects where each effect are declared in a variable.
Therefore, I bring all of these four variables and place them within an array called arr in which is used in the clickByItself() function using Math.floor(Math.random()) methods.
Without the for loop, the code clicks by itself randomly in one of the four buttons every time I reload the page.
function clickByItself() {
let random = Math.floor(Math.random() * arr.length);
$(arr[random]).click();
}
However, using the for loop I am not being able to make these clicks one-by-one within the maximum of 10 times.
var blueButtonEffect = code effect here;
var redButtonEffect = code effect here;
var greenButtonEffect = code effect here;
var yellowButtonEffect = code effect here;
var arr = [blueButtonEffect, redButtonEffect, greenButtonEffect, yellowButtonEffect];
//will click on buttons randomly
function clickByItself() {
let random = Math.floor(Math.random() * arr.length)
var i;
for (i = 0; i < 10; i++) {
$(arr[random]).click();
setTimeout(clickByItself(), 1000);
}
}
The final output with the current code above is the four buttons being clicked at the same time, not one-by-one.
So, how can I have this function to press a random button by 10 times one-by-one with one second of interval from each click?
To fix your code you need:
A base case for your recursion
Pass a function reference to setTimeout. Currently, you are executing clickByItself and passing its return value (which is undefined) to setTimeout.
Do not use setTimeout in a loop without increasing the time by a factor of i, as the for loop will queue all the function calls at the same time
Alternatively, you can use a "times" argument to avoid looping
You could try something like
function clickByItself(times = 0) {
let random = Math.floor(Math.random() * arr.length)
$(arr[random]).click();
if (++times < 10) {
setTimeout(function(){clickByItself(times);}, 1000);
}
}
An example with console logs
https://jsfiddle.net/pfsrLwh3/
The problem is that the for loop calls the setTimeout 10 times very quickly. If you want to wait until the previous function call finishes prior to calling the next, then you should use recursion or just use a setInterval.
Recursion:
function clickByItself(numIterations) {
let random = Math.floor(Math.random() * arr.length)
let i;
$(arr[random]).click();
if( numIterations < 10 ){
setTimeout(() => {
clickByItself(numIterations += 1)
}, 1000)
}
}
clickByItself(0);
With setInterval
let numIterations = 0;
function clickByItself() {
let random = Math.floor(Math.random() * arr.length);
let i;
$(arr[random]).click();
numIterations += 1;
if( numIterations > 10) {
clearInterval(loop)
}
}
let loop = setInterval(test2, 1000);
Are you saying this is working for only 4 times but I think your above code will run in an infinite loop as you are calling clickByItself() again in the for loop.
If you want press a random button by 10 times one-by-one with one second of interval from each click then replace the for loop with
for (i = 0; i < 10; i++) {
setTimeout($(arr[random]).click(), 1000);
}
I have created a function to get the average of an incoming signal over time. The end goal is to get a singular average number from a microphone signal every five minutes, but I have put two seconds in the setInterval part to speed up the testing process. I've tried out some code using RMS equations, but I cannot seem to figure out what is going wrong.
The absoluteLevel is the incoming linear level between 0 and 1, which is being produced in a function above. The absoluteLevel variable is global. The sample rate is set to 44100.
Thanks in advance.
function measureLevel() {
rmsTotal = Math.pow(absoluteLevel, 2) / sampleRate;
counter++;
if (counter === sampleRate) {
rmsAverage = rmsTotal / counter;
counter = 0;
rmsTotal = 0;
}
console.log(rmsTotal);
}
window.setInterval(measureLevel, 2000);
I've assume that all of your variables were initialized already, and available like absoluteLevel. From what I can see there could be two problems:
rmsTotal was getting reset each time instead of accumulating.
I changed the name to 'meanSquare'
You need the square root of that mean square (average of squares)
I renamed rmsAverage to 'rootMeanSquare'
So I would suggest:
function measureLevel() {
meanSquare += Math.pow(absoluteLevel, 2) / sampleRate;
counter++;
if (counter === sampleRate) {
rootMeanSquare = Math.pow(meanSquare, 0.5);
console.log('Counter reached. RMS: ' + rootMeanSquare);
counter = 0;
meanSquare = 0;
}
console.log(meanSquare);
}
window.setInterval(measureLevel, 2000);
I do have a worry though for you. If you run this function once every 2 seconds, and need 44100 samples for a rms, then you'll need 88200 seconds before you get your RMS output!!
If you can get your absoluteLevel very quickly, you might get a faster test with a loop:
function measureLevel() {
counter = 0;
meanSquare = 0;
while counter < sampleRate {
//RUN A SET ABSOLUTE LEVEL FUNC
meanSquare += Math.pow(absoluteLevel, 2) / sampleRate;
counter++;
console.log(meanSquare);
}
rootMeanSquare = Math.pow(meanSquare, 0.5);
console.log('Counter reached. RMS: ' + rootMeanSquare);
}
window.setInterval(measureLevel, 2000);
I am learning javascript to enhance some of my daily work, and so I am learning the basics.
I am still pretty green with the syntax, but am picking up on the language pretty quickly.
What I am trying to understand is how i can create a terminating condition that is evaluating a function.
I know the coding is wrong here, which is what I am trying to fix - I attempted a bunch of different things, but I am having trouble evaluating the loop based on my product.
I tried using return to store the value each iteration, but every attempt resulted in the script flat out failing.
What I want the script to do is to stop the loop when my product reaches <=100.
The problem is, my research suggests that the loop criteria can ONLY be referencing the variable, i.
I'm stuck in terms of how to look at the resulting product as the terminating condition.
var one = 5;
var two = 10;
var end = 100;
function mult (one, two) {
var product = one * two;
document.writeln(product + "<br>");
}
for (var i = 1; i <= end; i++)
mult(i, two);
If you want your loop to terminate when the product is <= 100, use an if statement to decide whether you want to write a line.
I've changed some variable names to make it easier to understand.
/*var one = 5;*/ /*This is never being used*/
var ten = 10;
var end = 100;
function mult (a, b){
var product = a * b;
if (product <= 100){
document.writeln(product + "<br>");
}
}
for (var i = 1; i <= end; i++){
mult(i, ten);
}
"the loop criteria can ONLY be referencing the variable, i." that's false!
You can define multiple conditions in a for loop.
To access the 'product' variable after loop execution you can declare it in the outer scope of the mult() function (or you can rewrite the mult() function to returns the product variable).
Like this:
var two = 10;
var end = 100;
var someNumberGtThan100 = 100000;
var lastProduct = 0;
var product = 0;
function mult (one, two) {
lastProduct = product;
product = one * two;
document.writeln(product + "<br>");
}
for (var i = 1; i <= someNumberGtThan100 && product <= 100; i++) {
mult(i, two);
}
console.log(lastProduct); // 100
By using this condition you have to store the previous value in an auxiliary variable, because when 'product' reach the value of 100 the loop condition is still true, so the loop will be executed one time more.
I have a simple setInterval function that is done inside of a for loop. My goal is that I want the function to run on each position in the array, and once it reaches the end, I want it to stop. However, this is not happening. The timeout function is continuing to run infinitely. Can anyone explain where I'm going wrong and what I need to do to fix this?
JS
Keyhole.bufferArray = [Keyhole.twoMileBuffer, Keyhole.fiveMileBuffer, Keyhole.tenMileBuffer, Keyhole.twentyFiveMileBuffer];
var ticker = -1;
for(var i = 0; i < Keyhole.bufferArray.length; i++){
var populateServices = setInterval(function(){
++ticker;
addBuffersToService(Keyhole, i);
if(ticker >= Keyhole.bufferArray.length - 1){
ticker = -1;
clearInterval(populateServices);
}
}, 1000)
}
function addBuffersToService(Keyhole, index){
console.log(Keyhole);
}
Because you have a for loop that is making an interval for every index of the array. You should not be using the for loop if you are looping over the array with the interval. Remove the for loop.
The problem is that you overwrite your interval handler in loop. I suggest you to kepp handlers in array and remove them according to iterator varialble:
var ticker = -1;
var populateServices = [];
for(var i = 0; i < Keyhole.bufferArray.length; i++){
populateServices[ticker + 1] = setInterval(function(){
...
clearInterval(populateServices[ticker + 1]);
ticker = -1;
Note that array identifiers should be positive numbers so you should add +1 inside handlers array.
And don't forget to set ticker to -1 after clearInterval invokation.
Here is my code and I am trying to practice making a for and a while loop with the while loop making use of a random number.
for(var i=0;i<5;i++){
console.log("This is a for loop");
}
var random= Math.random();
while(random<0.5){
console.log("This is a while loop");
random =Math.random();
}
It seems to not display the number however when I change the penultimate line to be:
var random =Math.random();
Sorry I'm quite new to coding so if this question is stupid I apologise in advance
There is a 50% chance that the while condition will be false on the first attempt. In such cases you will never see the loop's body being run.
var random = Math.random();
console.log('Initial value of random is', random);
if (random >= 0.5) console.warn('the while loop will not run');
while(random < 0.5) {
console.log("This is a while loop");
random = Math.random();
}
In your case, you may have wanted to write a do..while loop
var random;
do { // go into this block
console.log("This is a while loop");
random = Math.random();
} while (random < 0.5); // if condition true, go back to the `do`
If you're just starting with loops, it may be useful to consider how to re-write for loops as while loops
var i = 0;
while (i < 5) {
console.log("This is a while loop");
i++;
}
This isn't so you use while instead of for when a for is more natural, but so you get a feel for while loops, how they work and how sometimes they will suit the code you're trying to write.
for(var i=0;i<5;i++){
console.log("this is a for loop. the variable is:" + i);
}
var random= Math.random();
while(random<0.5){
console.log("This is a while loop the variable is:" + random);
random =Math.random();
}