How do I reset the count when a condition is met? - javascript

I'm trying to reset the count to 0 when conditions 1 or 2 are met when looping through one function every 2 seconds. At what point would I implement the reset. For example;
var timer;
var a = 'door';
var b = '';//this is set by an ajax call that fires off every second
var count = 0;
function condition(){
//condition 1
if(a == 'door' && b == 'inside' && count < 30){
$('#action').html('Person A');
count++;
//after 1 minute show 1 minute sign
} else {
$('#action').html('It\'s been 1 minute');
count = 31;
}
//condition 2
if(a == 'door' && b == 'outside' && count < 30){
$('#action').html('Person B');
count++;
//after 1 minute show 1 minute sign
} else {
$('#action').html('It\'s been 1 minute');
count = 31;
}
//condition 3
//empty div & reset count
if(b == ''){
$('#action').empty();
count = 0;
}
//set interval
clearInterval(timer);
timer = setInterval(condition, 2000);// 2 seconds x 30 = 1 minute
}
condition();

There's something off with your code, specifically for the setInterval function. The first parameter should be a function object, NOT the invokation of a function:
Should be this:
setInterval( condition, 2000 );

Related

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.

Javascript check counter and repeat function

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().

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
}

Javascript: + 1 Limit for Counter/Conditional Statement

In my javascript game i have a function that is called every 0.1 seconds with setInterval:
updateTimerID = setInterval(function(e) {checkProgress();}, 100);
I store a users score in a variable and have a conditional statement inside the checkProgress function which checks when my slider x position falls between 45 - 48:
var score = 0;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 ) {
score = score + 1
}
}
I then increase the score variable by one when this happens. The problem i have is i only want the score to be updated by 1 every time, not everytime - so with my function being called every .1 seconds - at the moment my score is adding at least 3 each time
if( slider_1.x => 50 && slider_1.x <= 60 ) {
score ++;
}
Can i limit it to 1 each time?
Something like this maybe?:
var isOver = false;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 && !isOver ) {
score = score + 1;
isOver = true;
} else if( slider_1.x < 45 && slider_1.x > 48 ) {
isOver = false;
}
}
you can do that by storing the score update time at a variable than substract it from current time to look for the time passed from last update is greater than 1 second
var score = 0;
var last_update =0;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 && ((new Date().getTime()-last_update) > 1000) ) {
score = score + 1
last_update=new Date().getTime();
}
}
Something like this will do the trick
var score = 0;
var inc = true;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 ) {
if(inc)
{
score = score + 1
inc = false;
}
}
if(slider_1.x < 45 || slider_1.x > 48)
{
inc = true;
}
}

Timer doesnt end when it reaches zero

I have been working on this javascript timer and can't understand why it doesnt stop when the hours, minutes and seconds are equal to zero.
Code:
var s= 18000;
var h= Math.floor(s/3600);
s-= h*3600;
var m= Math.floor(s/60);
s -= m*60;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
if(s == 0 ){
if(m == 0){
h=h-1;
s=59;
m=59;
if(h == 0){
clearInterval(counter);
}
} else {
m=m-1;
s=59;
}
//Do code for showing the number of seconds here
} else {
s = s - 1;
}
document.getElementById("timer").innerHTML=h+'hrs '+m+'min '+s+'secs ';
}
The problem I see here is that you'll decrement h variable by 1 when all time variables - and by time variables I mean h, m and s are set to zero:
if(s == 0 ) {
if(m == 0) {
h=h-1;
s=59;
m=59;
// more code goes here
So h will be -1 and the timer will never stop.
The best I can propose is to rewrite your timer completely, and use only seconds here. Every time the timer function gets invoked you check if s equals to zero - if it is, you stop the timer. Otherwise, you decrement s by 1. To update the inner HTML of #timer element you can recalculate the number of hours, minutes and seconds on the every invocation of timer method - this solution will be a lot more easier to understand and maintain than the chain of nested conditional statements.
The problem appears to be the logic in this section here...
if(s == 0 ){
if(m == 0){
h=h-1; // what if h is also 0 here?? this would set it negative
s=59;
m=59;
if(h == 0){
clearInterval(counter);
}
I think you should be doing your if(h==0) check sooner... before you decrement the values. So you might want to start your if else block with a if (s == 0 && m == 00 && h == 0) and use that to clear the interval. If everything is already zero, you don't want to change any more values.

Categories

Resources