How to repeat `setInterval`? - javascript

How can i repeat setInterval?
So, i have a function (Duration = 19sec for 1 itteration).
First 4 seconds - label is "text 1",
Next 7 seconds - label is "text 2"
And next 8 seconds - label is "text 3".
And after 19s it should repeat (I have var of itterations - newCurrentElement) and i also have the hole duration of the function (timeNewCurremtElement).
timeNewCurremtElement and newCurrentElement are known, so you shouldn't worry about it.
I have tried to make a loop (for), but that did't work.
function TextChanger() {
counter = 0;
clearInterval(timer);
function TextChanger_Interval(){
timer = setInterval(function() {
counter++;
if (counter <= 3) {
$('#in-hold-out').html("Inhale");
} else if (counter <= 10) {
$('#in-hold-out').html("Hold");
} else if (counter <= 18) {
$('#in-hold-out').html("Exhale");
} else {
counter = 0;
clearInterval(timer);
}
}, 1000);
}
TextChanger_Interval();
}
TextChanger();
Thank you!

You could take an object with the time for changing the text and the text as value.
To illustrate, this example shows unchanged counting as well. if not used, delete the else part.
setInterval((i => () => {
const parts = { 0: 'text1', 4: 'text2', 11: 'text3' };
if (parts[i]) console.log(parts[i]);
else console.log(i);
i++;
i %= 19;
})(0), 1000);

I think you are trying to do something like this
let counter = 0;
function TextChanger() {
if (counter <= 3) {
console.log(0);
} else if (counter <= 10) {
console.log(1);
} else if (counter <= 18) {
console.log(3);
} else {
counter = 0;
}
counter++
}
setInterval(TextChanger, 1000);

Related

Why is my Javascript fizzbuzz code not working?

I am trying to create a JS function that will print Fizz when a number divisible by 3 appears and Buzz if it is divisible by 5 and Fizzbuzz if both 5 and 3 but keeps printing "undefined" on chrome>sources>snippets. I have previously managed to run JS there but now it is just printing "undefined". Please help what is wrong with my code? Thank you in advance
This is my code:
var output = [];
var count = 1;
function fizzBuzz() {
if (count % 3 === 0) {
output.push("Fizz");
}
if (count % 5 === 0) {
output.push("Buzz");
}
if (count % 15 === 0) {
output.push("FizzBuzz");
} else {
output.push(count);
}
count++;
console.log(output);
};
You need to call the function using fizzBuzz(). You'd likely want to do this in a loop until it reaches a certain number.
In the example below, I use a while loop to call the function until count reaches 100. I've also moved the console.log() call to the end of the loop, as it doesn't make sense to log the entire array after each iteration.
Also, consider using else if statements so that Fizz or Buzz are only pushed if FizzBuzz has not been pushed. Otherwise, you may find that all three are pushed instead of just FizzBuzz.
var output = [];
var count = 1;
function fizzBuzz() {
if (count % 15 === 0) {
output.push("FizzBuzz");
}
else if (count % 3 === 0) {
output.push("Fizz");
}
else if (count % 5 === 0) {
output.push("Buzz");
}
else {
output.push(count);
}
count++;
};
while(count < 100) {
fizzBuzz();
}
console.log(output)
Try This
var output = [];
function fizzBuzz(i) {
if (i % 3 == 0 && i % 5 == 0) {
output.push("FizzBuzz");
} else if (i % 3 == 0) {
output.push("Fizz");
} else if (i % 5 == 0) {
output.push("Buzz");
} else {
output.push(i)
}
console.log(output)
};
fizzBuzz(15)
var output = [];
var count = 1;
function fizzBuzz() {
if (count % 3 === 0 && count % 5 === 0) {
output.push("FizzBuzz");
}
else if (count % 3 === 0) {
output.push("Fizz");
}
else if (count % 5 === 0) {
output.push("Buzz");
}
else {
output.push(count);
}
count++;
};
while(count < 100) {
fizzBuzz();
}
console.log(output)

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)

How to create dynamic IF statement?

I want to make condition of IF statement dynamically in javascript
example :
function checkNumber(number) {
var dynamicStatement = 1000000; // IF statement stop 1 million
if(number <= 1000) {
return 1000;
} else if(number <= 2000)
return 2000;
} else if(number <= 3000)
return 3000;
} else if(number <= 4000)
return 4000;
} else if (...) {
return ...
} else if (number <= 1000000) {
return 1000000;
}
}
Please help, thank you.
You can use:
Math.ceil(number/1000)*1000;
This will return the value nearest to the multiplier with 1000. For eg. if number is 900 then it will return 1000, if number is 1050 it will return 2000 and so on.
function checkNumber(number, limit, step) {
for(let i = 0; i < limit; i = i+step) {
if(number <= i) {
return i;
}
}
throw "Invalid Number";
}
checkNumber(75006, 1000000, 1000)
That answer Bhojendra posted is simple and beautiful, it's probably the one that suits your situation best.
Here's another, using for-loop:
function checkNumber(number) {
var dynamicStatement = 1000000;
var thousands = dynamicStatement / 1000;
for(var i = 0; i<thousands; i++){
if(number <= thousands * i){
return thousands * i;
}
}
return -1;
}

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

Categories

Resources