Javascript check counter and repeat function - javascript

I have an html page and I'm using JavaScript to create a function that display 2 images (the first between second 5 and second 10 and the second image between second 10 and second 20) and repeat that every 30 seconds.
I tried
var cmp=0
function main() {
window.setTimeout(main,30000);
cmp+1;
if (cmp >= 5 and cmp < 10)
show_image_1 ();
if (cmp >= 10 and cmp < 15)
show_image_2 ();
}
but I didn't find out how to check the time every second.

Define an Interval, and then display the image based on that:
window.setInterval(updateImg, 1000);
var timer = 0;
var imageSrc = document.getElementById("imageSrc");
imageSrc.style.display = "none";
function updateImg() {
timer += 1;
if (timer > 30) {
timer = 0;
}
if (timer >= 5 && timer <= 10) {
imageSrc.style.display = "block";
imageSrc.src = "http://lorempicsum.com/futurama/255/200/1";
} else if (timer >= 10 && timer <= 20) {
imageSrc.style.display = "block";
imageSrc.src = "http://lorempicsum.com/futurama/255/200/2";
} else {
imageSrc.style.display = "none";
}
}
<img src="" id="imageSrc">
JsFiddle: http://jsfiddle.net/ghorg12110/z6vfn1nb/

Here is my proposal:
// Define the images and the duration of each one in seconds (a missing "src" means the image will be empty):
var steps=[
{duration: 2},
{duration: 3, src:'one.jpg'},
{duration: 5, src:'two.jpg'},
{duration: 5},
];
// Index of current step: Will cylce from 0 to steps.length:
var currentStep=0;
// Periodic function to show the current step, and re-invokes itself cyclically:
function nextStep()
{
var step=steps[currentStep];
var img=document.getElementById("myimg");
if (step.src)
{
img.src=step.src;
img.style.visibility="visible";
}
else
{
// When there is no "src" in the current step: Hide the image:
img.style.visibility="hidden";
}
currentStep=(++currentStep % steps.length);
setTimeout(nextStep, 1000*step.duration);
}
To start the cycle, you have to call nextStep().

Related

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.

Delay in for-loop

I want to loop over an array and assign a color on each iteration. When the color is set, I want to delay until the next iteration before changing the color again.
This is the code I currently have but I could not create the delay between each iteration of the for-loop over the just1 array.
var colors = new Array("Good","Warning","Bad");
var crntcolor= 0;
just1=[[2.8077203491999057, -1.0756484331027858], [5.4610502752805568, -1.1574541704299315], [2.414925300315495, -1.506728995633369], [11.3143165555403673, -1.4461945021353346]];
function ChangeText()
{
document.getElementById('changeText').innerHTML = colors[crntcolor];
for(i=0; i<just1.length; i++)
{
if(just1[i][0] >= -5 && just1[i][0] <= 5)
{
crntcolor =0;
}
else if (just1[i][0] > 5 && just1[i][0] <= 10)
{
crntcolor = 1;
}
else if (just1[i][0] > 10)
{
crntcolor = 2;
}
setTimeout("ChangeText();",1000);
}
}
ChangeText();
I suppose what you want to do is loop over the array and between each element have a delay. You need to get rid of the for loop and change the text only for one element at a time:
var colors = new Array("Good","Warning","Bad");
var crntcolor= 0;
var just1 = [[2.8077203491999057, -1.0756484331027858], [5.4610502752805568, -1.1574541704299315], [2.414925300315495, -1.506728995633369], [11.3143165555403673, -1.4461945021353346]];
function ChangeText(index)
{
document.getElementById('changeText').innerHTML = colors[crntcolor];
if(just1[index][0] >= -5 && just1[index][0] <= 5)
{
crntcolor =0;
}
else if (just1[index][0] > 5 && just1[index][0] <= 10)
{
crntcolor = 1;
}
else if (just1[index][0] > 10)
{
crntcolor = 2;
}
if(index < just1.length)
{
setTimeout(function() { ChangeText(index+1); },1000);
}
}
ChangeText(0);
I'm not sure what you mean by the delay between the text specific to the array data present in just1. As far as I can tell, you have specified a fixed delay (1000). Do you mean you want a different delay based on the value of what's in your array? If so, you can alter the value in the loop:
setTimeout(function() { ChangeText(index+1); },1000 * just1[index][0]);
this would set the delay to
2.8, 5.45, 2.41 and 11.31 respectively when you loop through the array

How can I delay a loop depending on a condition?

I want to create a delay in a loop depending on a condition. Say, I have this:
var maxLoops = 50;
var counter = 0;
(function next() {
if (counter++ >= maxLoops) {
return;
}
setTimeout(function() {
console.log(counter);
next();
}, 100);
})();
Is there any way to pause the process for 2 seconds only when the counter is equal to 10, 20 or 30? So it should print:
1....10
(delay for a custom period of time)
11....20
(delay for a custom period of time)
21....30
(delay for a custom period of time)
31...50
The bottom line is, I don't want to delay at all when the counter isn't equal to 10, 20, 30.
Sure you can do that just change the timeout when you have a multiple of 10.
var maxLoops = 50;
var counter = 0;
(function next() {
counter += 1
var timeout_duration = counter % 10 == 0 ? 2000 : 0;
if (counter >= maxLoops) {
return;
}
setTimeout(function() {
console.log(counter);
next();
}, timeout_duration);
})();
That said, there need some few improvments because maxLoops and counter are defined on the global scope. Make it a function.
function loop (maxLoops, start) {
var counter = start || 0;
(function next() {
counter += 1
var timeout_duration = counter % 10 == 0 ? 2000 : 100;
if (counter >= maxLoops) {
return;
}
setTimeout(function() {
console.log(counter);
next();
}, timeout_duration);
})();
}
loop(50);
If you don't want to call next when counter isn't a multiple of 10, then you can add a usual loop in between the calls.
function loop (maxLoops, start) {
var counter = start || 0;
var timeout_duration = 2000;
(function next() {
while(counter < maxLoops && counter % 10 != 0) {
counter += 1
}
if (counter >= maxLoops) {
return;
}
setTimeout(function() {
console.log(counter);
next();
}, timeout_duration);
})();
}
loop(50);
That said, keep in mind that a setTimeout of 2000 doesn't mean exactly 2 seconds, but not less than 2 seconds. If somehwere, there is a loop that breaks the thread, the setTimeout could be never called as Javascript is single threaded and there is no fact that the function will be called after 2 seconds. If you're planning to use setTimeout to measure something within time, you might have to plan something else that will include the Date object for timings.
You can just use the setTimeout() with a different timing based on your counter:
var maxLoops = 50;
var counter = 0;
(function next() {
if (counter++ >= maxLoops) {
return;
}
var delay = 0;
// on multiples of 10, use a longer counter
if (counter % 10 === 0) {
delay = 2000;
}
setTimeout(function() {
console.log(counter);
next();
}, delay);
})();
Or, you could skip the setTimeout() completely when you don't need the delay.
var maxLoops = 50;
var counter = 0;
(function next() {
if (counter++ >= maxLoops) {
return;
}
// on multiples of 10, use a longer counter
if (counter % 10 === 0) {
setTimeout(function() {
console.log(counter);
next();
}, 2000);
} else {
console.log(counter);
next();
}
})();
Or, rather than recursion, you can just use a while loop as in this working snippet:
var maxLoops = 50;
var counter = 0;
(function next() {
// while we haven't hit maxLoops and while not a multiple of 10
while (counter < maxLoops && counter % 10 !== 0 && counter !== 0) {
log(counter);
++counter;
}
if (counter < maxLoops) {
setTimeout(function() {
log(counter);
++counter;
next();
}, 1000);
}
})();
function log(x) {
var div = document.createElement("span");
div.innerHTML = x + " ";
document.body.appendChild(div);
}

Javascript if statement set a time on the condition

I have an if statement with the condition that if numberOfFingers == 5 then the counter will increase by 1, I want the counter to increase by 1 only if the duration of numberOfFingers is 5 seconds. (this is with the leap motion) Is this possible?
if (numberOfFingers == 5) {
var start = parseInt(document.getElementById('count').innerHTML);
var end = start+1;
document.getElementById('count').innerHTML = end;
}
have a look at "setTimeout" and try something like this:
if(numberOfFingers == 5) {
setTimeout(function(){
if(numberOfFingers == 5){ //5 fingers still after 5s
var start = parseInt(document.getElementById('count').innerHTML);
var end = start+1;
document.getElementById('count').innerHTML = end;
}
}, 5*1000); //your 5s
}

Categories

Resources