stop javascript loop, setTimeout - javascript

This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.
I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.
setTimeout(function() {
createSnow(20);
loop();
}, 10000)
here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

You were close. You just needed a way to tell the system to stop the animation loop. See my codepen: https://codepen.io/intervalia/pen/zPPoBZ
I added a variable to indicate if animation should be happening:
var animating = true;
A routine to stop the animation:
function stopAnimation() {
animating = false;
//Add something in here to clear the screen
}
A validation check in the animation loop:
function loop() {
if (animating) {
draw();
update();
animFrame(loop);
}
}
And changed your timeout to turn off the animation:
createSnow(150);
loop();
setTimeout(stopAnimation, 10000);
Cool animation!!

What you'll want to do is create a "timer", finding the difference between when you started and the current time.
I'm not sure if you wanted createSnow(20) inside of the loop or not, so I put it before, as initialization.
createSnow(20);
const start = new Date();
while(new Date() - start < 10000) {
loop();
}

Use cancelAnimationFrame.
Sample usage
Declare cancelAnimFrame:
var cancelAnimFrame =
window.cancelAnimationFrame ||
window.mozcancelAnimationFrame ||
window.webkitcancelAnimationFrame ||
window.mscancelAnimationFrame;
Update loop function:
var animId;
function loop() {
draw();
update();
animId = animFrame(loop);
}
and use animId to stop animation.
(As already mentioned, starting snowing should be out of setTimeout.)
createSnow(20);
loop();
setTimeout(function() {
cancelAnimFrame(animId)
}, 1000)

the only thing that you have to change is a little change of your code plz see this code below :
var timeOut = setTimeout(function() {
createSnow(20);
loop();
}, 10000);
clearTimeout(timeOut);

Related

How can I depend on the interval that I just cleared in jquery?

It's a follow up to this question - https://stackoverflow.com/a/33430608/3766930
Basically I have a text area and when user starts typing in sth, the counter starts going down from 3 to 0. when it reaches 0 it gets disabled.
Now I want to add a feature of starting over - when user clicks the link start over, text area goes enabled again and user has 3 seconds (again) to perform the input.
I modified the jquery script:
$('#textArea').on('input propertychange', display30Seconds);
var interval;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
}
}, 1000);
}
but I see that I cannot call the method display30Seconds(); again. Or rather I can, but the interval is not set again. How can I fix it?
Seems like I'm not entering the code inside
if (!interval)
because the interval is not visible any more after clearing it (?). So I thought about moving the var interval; into the body of the method function display30Seconds() {, but that doesn't bring the expected effect. Is there a way of fixing it?
Here is my updated fiddle: http://jsfiddle.net/jf4ea4nx/3/
Set interval=null after the clearInterval() call.
What seems to confuse you is the semantics of clearInterval(interval). As Patrick Evans points out in his comment, it will not set interval to a value that evaluates to false in a condition.
To make it completely clear you could use a boolean variable such as countdownRunning in addition to the interval variable to keep track of whether the countdown is active or not.
Try this:
$('#textArea').on('input propertychange', display30Seconds);
var interval=false;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$(document).on('click','#counterIsDone', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
interval=false;
}
}, 1000);
}
You can improve your code by using a conditional recursive call to to your iterative function instead - each call has a one second delay, which makes it slightly more intuitive to use (think of each call as one tick):
var seconds = 3;
$('#textArea').on('input propertychange', setTimeout(timeout.bind(null, seconds), 1000));
function timeout (iterations) {
$('#counter').html(iterations);
if (iterations === 0) {
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
timeout(seconds);
});
}
else {
setTimeout(timeout.bind(null, --iterations), 1000);
}
}
The bind function simply binds the arguments of the bind function to the arguments of the timeout call - the first argument to the bind function declares its this scope; but don't worry about that too much.
You can modify the duration of the timer by changing the seconds var. Hope this helps :)

Control width expand onClick while setInterval, js,html5

I have setInterval problem. I made something similar to load bar. When I click mouse I fire expanding width of my block called loadBar1
// here preset of interval and loadbar...
var interval = 0;
createLoadBar1 = function() {
loadBar1 = {
// another stuff
width:0,
};
document.onclick = function (mouse) {
interval = setInterval(expandLoadBar1, 60);
}
It's expands by the help of this function:
function expandLoadBar1() {
if(loadBar1.width < 60) {
loadBar1.width++;
}
if (loadBar1.width >= 60) {
loadBar1.width = 0;
clearInterval(interval);
}
}
It's very simple above and works well when I click just once but I start having problems when I click more that one time by mouse clicking, it's logically cause the faster loadBar1.width expanding twice and after second or more mouse click the clearInterval for interval stops working and just continue raising expanding speed when I click more.
You probably need to clear the interval when the user clicks:
document.onclick = function () {
clearInterval(interval);
interval = setInterval(expandLoadBar1, 60);
}

How to pause and resume jquery interval

I have made a custom slider with jQuery. For this I have used setInterval function:
timer = setInterval(function() {}, 8000);
But I cannot pause and resume the interval. I have 2 buttons (play, pause) which I want to use for. Lets say I click pause after 3 sec, and then resume it. So it should stay in that slider for 5 more seconds and then go to the next one and continue 8 seconds each. I have seen this kinda slider with mouseover pause, but can't do it by myself. I have tried this:
clearInterval(timer);
But this seems reset the interval, don't pause. Can anyone help :)
I'm not entirely sure that's something native to jQuery, however, you could use a flag to pause it, and check in your setInterval whether to execute.
Edit:
Found something that might be useful to you, the jquery-timer
Alternitively, you can keep track of the id set by setInterval, and clear out out when you'd like to pause. Then you can set it again when you wish to resume:
var id = window.setInterval(<code>); //create
window.clearInterval(id); //pause
id = window.setInterval(<code>); //resume
there are two ways of accomplish this:
Clearing the interval everytime you pause and starting a new interval when you resume it.
Having a flag to tell the function in the interval when it is paused and it should not do anything.
The first solution would work like this:
let intervalId = false;
const intervalLength = 8000; // 8 seconds
function intervalFunction () {
// do stuff.
}
startButton.onclick = function () {
if (intervalId === false) {
intervalId = setInterval(intervalFunction, intervalLength);
}
}
pauseButton.onclick = function () {
if (intervalId !== false) {
clearInterval(intervalId);
intervalId = false;
}
}
// auto start it:
intervalId = setInterval(intervalFunction, intervalLength);
The second solution would work like this:
var isRunning = true;
var interval = setInterval(function() {
if (!isRunning) {
// not running, do nothing
} else {
// it is running, do stuff.
}
}, 8000);
pauseButton.onclick = function () {
isRunning = false;
};
startButton.onclick = function () {
isRunning = true;
};
I am not complete sure, that what you are asking for, is the right thing you are showing us... setInterval basically is pure native javascript and in my opinion not worth using! If you wan't to set your timeouts via jquery try this link: http://jchavannes.com/jquery-timer. You can find usages there...
Now on to your problem... you need a state to check wether the slider has to slide or not... simply set a bool like this...
var timer;
var doSlide = false;
var i = 0;
function Slide(){
timer = setTimeout(function(){
if(doSlide == true){
Slide();
i++; // Same as i = i + 1
console.log('Sliding');
if(i == 3) AbortSlide(); /* Abort on third slide! Dont use this in your logic!*/
} else if(doSlide == false){
console.log('Sliding aborted untill next RunSlide() call!')
clearTimeout(timer);
}
},1000);
}
function AbortSlide(){
doSlide = false;
i = 0; // Resetting the count! Dont use this in your logic!
}
function RunSlide(){
doSlide = true;
Slide();
}
RunSlide();
You could also empty the interval in the abort method:
function AbortSlide(){
doSlide = false;
clearTimeout(timer);
i = 0; // Resetting the count! Dont use this in your logic!
}
Here is a working fiddle i made for you to understand what timers and intervals are for: https://jsfiddle.net/q5qzmv68/7/
Hope this helps! Cheers!

jQuery Fade object after 20 seconds of inactivity

I want to fade out a div if a user hasn't made a mouse click for 20 seconds.
I have the following code:
if($('.main-popup2').is(":visible")){
setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
Problem is I don't know how to reset the setTimeout after detecting a user mouse click.
Thanks!
The .setTimeout() method actually returns a reference to the timer it creates. This reference can be used in .clearTimeout to stop the timer before it executes.
Here is an example of how to use this:
var timer;
if($('.main-popup2').is(":visible")){
// create the timer and save its reference
timer = setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
// when clicking somewhere on the page, stop the timer
$(document).click(function() {
clearTimeout(timer);
}):
var timeout = null;
var fadeElement = $('.main-popup2');
function fader() {
if(null !== timeout) {
clearTimeout(timeout);
}
fadeElement.stop();
timeout = setTimeout(function () {fadeElement.fadeOut('fast');}, 2000);
}
$(document).click(fader);
fader();
Use delay function.
(window).click(function () {
$('.main-popup2').delay(6000).fadeOut(300);
}
Each click restart 6 seconds, after it .main-popup2 fadeout if there isn't

Stopping increment at specific height

I am animating images within a logo in a slot-machine type of animation. I need it to stop animating once it gets to the top of the image (and send a callback if possible).
Currently, this is how I'm accomplishing the animation:
window.setInterval(function() {
$('#title-1 img').animate({bottom : '-=60px'})
}, 5000);
Any ideas on how I would get it to stop, and to send the callback?
So I assume you have a sprite image containing multiple logos, you want them to slide each 5 seconds until you reach the last one, and then call the callback?
var cnt = 6,
$img = $('#title-1 img'),
i = 0;
function animate_logo(cb) {
if (i < cnt) {
$('#title-1 img').animate({bottom : '-=60px'});
i += 1;
setTimeout(function () {animate_logo(cb)}, 5000);
}
else {
cb();
}
}();
var interval = window.setInterval(function() {
$('#title-1 img').animate({bottom : '-=60px'},
function(){
if(`some stop point`) clearInterval(interval);
}
);
}, 5000);
I would not suggest using a setInterval when dealing with animations due to the way newer browsers are making changes to the way setInterval and setTimeout work when the tab is not the active tab.
var $title1 = $("#title-1");
var $title1img = $title1.find('img');
function anim(){
if ($title1.height() < parseInt($title1img.css("bottom"))) {
setTimeout(function(){
$title1img.animate({bottom : '-=60px'},anim);
},5000);
}
}
$title1img.animate({bottom : '-=60px'},anim);
Edit: another reason not to use setInterval to fire off animations is due to the reqeustAnimationFrame that was implemented in 1.6 and removed in 1.6.3, which will more than likely be added back in 1.7. If you write code now that will be compatible later, that's less maintenance you will have to do later if you end up being required to upgrade.
Here's a jsfiddle http://jsfiddle.net/czUnU/
Edit: function...
function animColumn(title,img){
function anim(){
if (title.height() < parseInt(img.css("bottom")) {
setTimeout(function(){
img.animate({bottom : '-=60px'},anim);
},5000);
}
}
img.animate({bottom : '-=60px'},anim);
}
animColumn($("#title-1"),$("#title-1 img"));
animColumn($("#title-2"),$("#title-2 img"));
animColumn($("#title-3"),$("#title-3 img"));
http://jsfiddle.net/czUnU/1/

Categories

Resources