Infinite Loop in Javascript? - javascript

I have an animation of a car driving back and forth across the screen and have figured out how to flip the image when it reaches the right side of the screen and then again when it reaches the left side. However, I need to loop this JS event so the animation constantly shows the car driving in the correct 'direction.' The code below should give you an idea of what I'm working with, so if anyone could be so kind as to help this beginner figure out how to make it loop infinitely, I would greatly appreciate it.
*tl/dr
Basically I need the code below to loop infinitely.
var carorange = $('.org-car');
setTimeout(function () {
carorange.addClass('flipimg');
}, 5000);
setTimeout(function () {
carorange.removeClass('flipimg');
}, 10000);

Use setInterval instead of setTimeout:
var carorange = $('.org-car');
setInterval(function () {
carorange.toggleClass('flipimg');
}, 5000);
setInterval has a nother big advantage: You can stop the interval. So if you assign the interval to a variable, like var myTimer = setInterval..., you can stop it at any time using clearInterval(myTimer); :)

Related

clearInterval does not reset the setinterval value

I'm making a slot machine simulator to learn javascript and messing around with setInterval() and clearInterval(). To simulate the slow stopping of the rows I set asetTimeout() to clear the Intervals of my 3 columns, but the timer doesn't reset the function is still called, I also tried a console log inside the setTimeout and the calls are correct 1sec after 2sec another log and then the third. what I'm doing wrong?
Here try the game and the full code with HTML: https://jsfiddle.net/orphtv1m/1/
//Here i initialize my setInterval
wheelIntervals[i] = setInterval(function(){
columns[i][numberStart[i]].style.background = "white";
numberStart[i] = (numberStart[i]+1)<10 ? numberStart[i]+1 : 0;
columns[i][numberStart[i]].style.background = "red";
},timer);
/*Code*/
setTimeout(function(){
//Here i try to clear it
console.log('Helo');
clearInterval(wheelIntervals[i]);
},i*1000);
}
setTimeout(endGame(), 3000);
}); ```
clearInterval(wheelInterval[i])
Will be always called with i equal to 2
Using setTimeout inside loops might be a little bit tricky because of closures.
Here is an explanation how to do it correctly: https://medium.com/#axionoso/watch-out-when-using-settimeout-in-for-loop-js-75a047e27a5f

Make javascript Animation function loop, Until page loads

I have a piece of javascript that I have copied & edited, that is designed for an animated loading ring but the animation only runs once, I would like it to run every 4 seconds, until the page is loaded, but I can't find the right syntax/script to get it to repeat, i do not want it to reload the page only loop that specific script until i set it to stop.
".radial" is the class of the radials contained inside my css & html files.
there is twelve of them & they do-not rotate only the fluorescent .glow animation part makes it appear as they are rotating. the code is;
const radials = [...document.querySelectorAll('.radial')];
let degrees = 29;
for(i=0; i < radials.length; i++) {
degrees += 13;
radials[i].style.transform = `rotate(${degrees}deg)`;
degrees += 34;
}
radials.forEach((radial, index) => {
setTimeout(function() {
radial.classList.add('glow');
},index * 29);
});
:: Update ::
Having read the comments below and searching on Youtube. I think that wrapping the whole script in a function, would be the best option. Including a call to that function within its self & passing it an argument in the parenthesis of a timeout or delay property. But setInterval() & setTimeOut() both use the unsafe eval() function underneath. Which is supposed to be a security concern.
Also a youtube video I watch a while ago, said that setInterval() & setTimeOut() do not achieve 60fps. requestAnimationFrame() Would be A much better option. I'm not sure how legitamate these claims are, or where his sources were from but I will continue searching the Webs.
The glow part looks good but I just haven't been able to get it to repeat.
I am new to Js please be patient.
is there any other workarounds for the setTimeOut() & setInterval().?
Place this code into a function that is passed to a setInterval() timer call.
function loop() {
const radials = [...document.querySelectorAll('.radial')];
let degrees = 29;
for(i=0; i < radials.length; i++) {
degrees += 13;
radials[i].style.transform = `rotate(${degrees}deg)`;
degrees += 34;
}
radials.forEach((radial, index) => {
setTimeout(function() {
radial.classList.add('glow');
},index * 29);
});
setTimeout(loop, 4000);
}
Use setInterval(). The setInterval takes two parameters, the first is the function you want to run and the second is your repeat time in miliseconds. So to run a function every 4 seconds you would do:
setInterval(function() {
// do something
}, 4000);
You can do it with setInterval, as in the other answers, but I think that the logic is clearer if you have an animate function that keeps calling itself.
You are adding a "glow" class, but you are never removing it. The animate function should toggle it on and off. To make it crystal clear, let's make that a separate function, toggleGlow.
Next, each animation loop we kick off the individual toggleGlow functions with a different delay for each radial.
Finally, the animate function will re-call itself after a short, constant, delay each time, until some stop condition is met (like the page loading).
const radials = [...document.querySelectorAll('.radial')];
function toggleGlow(element) {
if (element.classList.contains("glow")) {
element.classList.remove("glow");
} else {
element.classList.add("glow");
}
}
function animate() {
radials.forEach((radial, index) => {
setTimeout(function() {
toggleGlow(radial);
}, index * 29);
});
if (!stopCondition) {
setTimeout(animate, 200);
}
}
// kick it off
animate();
JSFiddle example here: https://jsfiddle.net/duxhy3Lj/

Stop javascript slideshow which is autoplaying using setInterval - Siema

I'm using the siema slideshow because it seems super nice and lightweight.
I want the slideshow to play when the user hovers their mouse over, and stop when they leave.
I've got the play bit working - using setInterval() - as per the guide docs, but I can't get the slideshow to stop. I'm trying to kill the interval, but that doesn't seem to work.
Here's my full code
const mySiema = new Siema({
duration: 250,
loop: true, // note: this just gets the slideshow to return to the beginning
});
const container = document.querySelector('.siema');
var timer, intervalInSec = 1000;
container.addEventListener('mouseenter', () => setInterval(() => mySiema.next(), intervalInSec));
container.addEventListener('mouseleave', clearInterval(timer));
and heres a codepen for fiddling with.
You need to assign timer to the output of the setInterval() method.
It (setInterval) returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval()
You also need to call an anonymous function on the mouse leave event to properly call clearInterval(). For example:
container.addEventListener('mouseenter', () => timer = setInterval(() => mySiema.next(), intervalInSec));
container.addEventListener('mouseleave', () => clearInterval(timer));

PIXI.extras.MovieClip catch end of loop

I am using PIXI.extras.MovieClip to play a short animation (about 60 frames) and due to not knowing how many FPS there will be on users device I can't tell how much time exactly does it take to play all the frames. setTimeout also does not guarantee that function will be triggered exactly after specified time so it's kinda not my way of solving this too.
When the playing of animation is finished I want to trigger some events in code to remove the MovieClip and write some logs.
The problem is that I can't find any kind of trigger/callback that will be called when last frame of animation was rendered.
example code:
movie = new PIXI.extras.MovieClip(someFrames);
movie.animationSpeed = 1;
movie.onComplete = animationFinished;
movie.play()
animationFinished = function () {
console.log("Animation just reached it's end.");
movie.gotoAndStop(0);
};
the obvious problem is, that movie.onComplete is never called. Is there any way to make this work?
Thanks for any suggestions and ideas.
Happy coding!
movie = new PIXI.extras.MovieClip(someFrames);
movie.animationSpeed = 1;
movie.onComplete = animationFinished;
movie.loop = false;
movie.play();
animationFinished = function () {
console.log("Animation just reached it's end.");
movie.gotoAndStop(0);
};

JavaScript Timer clearInterval complications

So I'm attempting to make a Pomodoro Timer without using an API (I know, stupid choice) but I feel as if I'm over-complicating this issue.
I forked my CodePen so I could post the current code here without confusing anyone. My Code Pen
To see my issue: Just set Timer to .1 and Break to .1 - You'll see the Start to Resume works fine, but the Resume to start has issues.
I built in consoleLogs to track it and I see the Work Timer TRIES to start but then breakTimer over-runs it, and duplicates on every pass.
Why isn't my clearInterval working?
Things I've tried:
Adjusting names of clearInterval,
Setting it so it goes back to startTimer instead of start
force quitting it (instead of looping it back to startInterval.
The function is virtually identical to my startFunction yet fails to work properly. Would appreciate any input (I'm new to clearInterval but I believe I am using it right.)
function breakTimer() {
$('.jumbotron').css('visibility', 'visible');
setInterval(function() {
console.log("Break Timer...");
breakTime--;
if (breakTime < 0) {
clearInterval(timer);
working = false;
start();
} else {
showTime(breakTime);
}
}, 1000);
}
Edit:
To answer the reply:
function start() {
if (working == true){ //This keeps it from being spammable
return;
} //Else
workTime = $('#work').val()*60;
breakTime = $('#break').val()*60;
working = true;
checkStatus();
timer = startTimer();
}
Unsure if I should post every Function here
As per definition, the value returned by setInterval(...) is the ID of the created timer. As such, with your code you can only stop the last created timer because the ID in the timer variable gets overwritten, causing it to lose control over the previously created (and still running) timers.
The ID is what you pass on to clearInterval(...) to stop a timer. You will have to do this in a different way. You may ask for a different way in https://codereview.stackexchange.com/

Categories

Resources