repeating for loop in javascript - javascript

I want to count from 0 to 199 three times in a row in 10 millisecond steps like 0 1 2 ... 198 199 0 1 2 .... 198 199 0 1 2 .... The first run is working fine with:
function count() {
time = 0;
for (var i = 0; i < 200; i++) {
time += 10;
setTimeout(function(j) {
return function() {
console.log(j);
}
}(i), time);
};
};
count();
but i do not get the desired result when calling the function three times like
for (var i = 0; i < 3; i++) {
count();
}
What is the right way for me?

I suppose that should be timed too:
for (var i = 0; i < 3; i++) {
setTimeout(animateRio /*or do you mean count?*/, i*2000);
}

You don't need to schedule all of your own timeouts, setInterval can call a function every unit of time. So create an interval that will run every 10 milliseconds. Then add a loop counter and use some modulo arithmetic.
var time = -1,
interval,
loop = 3;
interval = setInterval(function() {
time += 1;
if(time % 200 === 0) {
loop--;
}
if(loop < 0){
clearInterval(interval);
return;
}
console.log(time % 200);
}, 10);
JSFiddle

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.

How can I loop this if statement when I call a function

I want to call the boss[i].showBoss() and .moveBoss() functions every time the counter is 10,20,30,40...(dividable by 10), ( if(counter % 10 === 0) works only when the counter is at a number divisible by 10, not the others), but this hard-coded example only runs the code once after counter == 10, not when counter == 20,30,40 etc. Any suggestions on how I can can start the functions every time counter % 10 == 0, but not stop them after the counter is not % 10, for instance 11?
function draw() {
// put drawing code here
background(220);
if (counter >= 10) {
for(i = 0; i < boss.length; i++){
boss[i].showBoss();
boss[i].moveBoss();
}
} else if (counter >= 20) {
for(i = 0; i < boss.length; i++){
boss[i].showBoss();
boss[i].moveBoss();
}
} else if (counter >= 30) {
for(i = 0; i < boss.length; i++){
boss[i].showBoss();
boss[i].moveBoss();
}
}
}
Create an object to represent your boss action you want to start. When divisible by 10, create one of these and added to a list of bosses to draw. Every draw loop, draw all your bosses.
let bossesToDraw = [];
function draw(){
if(counter % 10 == 0){
bosses.push({
// state for the boss like its current position
// this could also create a new boss if you have a proper object
});
}
bosses.forEach(function(boss){
boss.showBoss();
boss.moveBoss()
});
//maybe check if you should remove the boss
}
You are kind of answering your own question here...
Can't you just do:
function draw() {
// put drawing code here
background(220);
if (counter % 10 === 0) {
for (i = 0; i < boss.length; i++) {
boss[i].showBoss();
boss[i].moveBoss();
}
}
}
The function draw() will run anyways. What you need to do is to check when your counter is divisible by 10, your instruction counter % 10 === 0 works fine for that.. Here I've mimic the draw function behaviour with a setInterval. Please note that the draw function is now an arrow function, that's to have access to the counter variable in the scope. This is irrelevent in your case.
let counter = 0;
let draw = () => {
// we do normal draw things
// background(255);
if(counter % 10 === 0) {
// we need to animate the boss.
console.log('current counter was divisible by 10', counter);
}
counter ++;
};
setInterval(draw, 100)

Javascript: Waiting for one (or multiple) condition in For Loop

I want to check a condition for k times for a value to be true, inside a For loop, each time I want to wait 2 seconds, after that I want to go next iteration of the for a loop. For example, I tried something like below -
var k = 0;
for (let i = 0; i < B.length; i++) {
setTimeout(function F_stTimer() {
if (B[i].innerText === "S") {
var A = "True"; //just for example
if (A === true && k == 0) {
// Do something
k = k + 1;
i = i - 1; // so , I can check the ith element again once start the loop again
} //if
else if (A === true && k > 0 && k < 5) { //checking 5 times for A to be false
k = k + 1;
}, i * 2000);
i = i - 1;
} //if
else if (A === true && k == 5) {
k = 0;
} //if
} // if
}, 5000);
} // i loop
But the above type of code is not working because I do not change when it is inside setTimeout.
Anyway, can anyone help me with the problem I have?
One does not need to follow the way I mentioned above, what I want to do is-
check a condition for k times for a value to be true, inside a For loop, each time I want wait t seconds (duration of each delay/interval of delay), after that, I want to go next iteration of the for a loop.
Plz comment for further clarification.
You could take an interval and check a counter.
var counter = 0,
interval = setInterval(function () {
counter++;
if (counter === 5) {
counter = 0;
console.log('five');
} else {
console.log('not five');
}
}, 1000);
You could write a function that takes two arguments:
howManyTimes - number of times you want to iterate
howOften - in what intervals you want to do the check (in milliseconds)
function checkInIntervals(howManyTimes, howOften) {
var counter = 0;
var interval = setInterval(function() {
counter++;
if (counter === howManyTimes) {
clearInterval(interval);
}
// do something
console.log(counter, 'iteration')
}, howOften)
}
// run the function
checkInIntervals(10, 2000);
Inside the interval the counter is incremented and when it's equal the the desired number of iterations, the interval is cleared and the execution stops.

looping from 1 to 50 after the automatic pause for 30 seconds and further looping to 51 to 100 and so on

How do I submit looping from 1 to 10. And then pause for 10 seconds. And then looping from 11 to 20. And so on
Please help me.
Here is the solution for your question:
var count = 0;
function counter (count) {
if(count < 50) {
var limit = count + 10;
for(var i = count; i <= limit; i++) {
console.log(i);
this.count = i;
}
}
}
counter(count);
setInterval(function() {
counter(count);
}, 10000);
Have fun and try to write code by yourself.

print number from 1 to 10 after every 2 seconds

i want to print number after every n number of seconds and based on few conditions i am changing the timer as well as i am stopping the print function. i have done like this --
var myfunc = {
value : 1,
running : false,
timer : 1000,
start : function(){
this.running = true;
clearInterval(this.timeout);
this.timeout = setTimeout(function() {
myfunc.execute(myfunc);
}, myfunc.timer);
},
execute : function(){
if(!this.running) return false;
console.log( 'Currently at -- ' + (this.value++) );
if (this.value > 5 ){
this.changetiming();
}
if (this.value > 10 ){
this.stop();
return;
}else{
this.start();
}
},
changetiming : function(){
this.timer = 3000;
},
stop : function(){
this.running = false;
clearTimeout(this.timeout);
}
};
myfunc.start();
Now i want to know what is wrong with following code --
for(var i = 0; i <= 10; i++){
print(i);
}
function print(i){
setTimeout(function(){
console.log(i)
},2000);
}
here is the right way and easy way to do this in ES6+:
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) {
setTimeout( () =>{
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);
by multiplying i , each setTimeout() to be delayed 2 to 20 seconds (2000 x 1, 2000 x 2…) respectively.
I'm pretty sure the question "Why does this JavaScript code
for (var i = 0; i <= 10; i++){
print(i);
}
function print(i) {
setTimeout(function(){
console.log(i)
},2000);
}
print out the values 1 through 10 at once, after 2 seconds have elapsed?" has been asked before.
It is a common mistake.
What you are doing is calling print 10 times. Each call to print takes only a few microseconds. Why? Because it just calls setTimeout. Executing setTimeout takes only a few microseconds to complete. All the call does is schedule something to take place in the future. So within a few microseconds you have scheduled 10 things to take place at about 2 seconds in the future. All the schedulings happen at about the same time. So all the console logs take place at about the same time, two seconds after you scheduled them.
See Satapal's comment to your question for a nice way to do what you want to do.
#easiestway
for (var i = 0; i <= 10; i++){
print(i);
}
function print(i) {
setTimeout(function(){
console.log(i)
},i*2000);
}
Using IIFE, Clouser, and Global Scoping
(function(numbers){
for(var i=0; i<numbers.length; i++){
(function(i){
setTimeout(console.log, i*2000, i+1)
})(i);
}
})(new Array(10))
OR IIFE and Local Scoping
(function(numbers){
for(let i=0; i<numbers.length; i++){
setTimeout(console.log, i*2000, i+1)
}
})(new Array(10))
for(var i = 0 ; i <= 10 ; i++) {
setTimeout( () => { console.log(i) }, i * 1000 );
}
Why we are not able to print 0 to 10 no with the help of var?
Why we are able to do with let?
You might want to try this:
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) setTimeout(console.log, i * 1000,i)
}
printNumbersForEvery2Sec(10);```
You can use timeout of javascript
function timer(n) {
for (let i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i);
}, i * n);
}
}
timer(2000);
In the above code timing is not coded so you can decide how much interval you want.
A more generalised solution:
function printNumbers(start, end, delay=1){
const interval = delay*1000
for(let i=start; i<=end; i++){
setTimeout(console.log, (i-start)*interval, i)
}
}
printNumbers(3, 10, 2) // firstNumber, lastNumber, timeInSeconds
for (let i = 1; i <= 10; i++) {
setTimeout(() => {
console.log(i)
}, (i * 2000) )
}
Far best! and easy solution... Checkout snippet...
for (let i = 1; i <= 10; i++) {
setTimeout(() => {
console.log(i)
}, (i * 2000) )
}
const RandomUnderHundredNumber = (min,max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; /*min and max numbers are included */
}
let inter
const testFunction = () => {
inter = setInterval(() => console.log(RandomUnderHundredNumber(0,99)), 1000) // generate number between 0 and 99 every 1 sec
}
testFunction();
setTimeout(function( ) { clearInterval(inter); }, 5000); /* clear interval after 5 sec delay (optional) */
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) {
setTimeout( () =>{
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);
There are two solution to this problem.
Using let keyword, local scope.
const printNumbers = (n) => {
for (let i = 1; i <= n; i++) {
setTimeout( () => {
console.log(i);
}, i * 2000);
}
}
printNumbers(5);
Using var keyword, functional scope with the help of closures.
Wrap the setTimeout function with another function which has the value of the variable at that instance. Which console's log the correct value.
Example is shown below.
const printNumbers = (n) => {
for (var i = 1; i <= n; i++) {
function helper(num){
setTimeout( () => {
console.log(num);
}, num * 2000);
}
helper(i);
}
}
printNumbers(5);

Categories

Resources