Stopping a running function in javascript/jquery on click event - javascript

I have a slideshow function in jquery that I want to stop on a particular click event. The slideshow function is here:
function slider(){
setInterval(function(){
var cur = $('img.active');
cur.fadeOut('fast');
cur.removeClass('active');
cur.css('opacity','0');
cur.addClass("hidden");
var nextimg;
if (!cur.hasClass("last")){
nextimg = cur.next("img");
}
else {
nextimg = cur.prev().prev().prev();
}
nextimg.removeClass("hidden").fadeIn('slow').css('opacity','1').addClass('active');
},5000);
}
I have been reading about .queue but not sure how I can use it exactly, can I call my function from a queue and then clear the queue on a click event? I cannot seem to figure out the syntax for getting it to work of if thats even possible. Any advice on this or another method to stop a running function on a click would be appreciated.

For what it's worth, it's generally advisable to use a recursive setTimeout instead of a setInterval. I made that change, as well as a few little syntax tweaks. But this is a basic implementation of what I think you want.
// Store a reference that will point to your timeout
var timer;
function slider(){
timer = setTimeout(function(){
var cur = $('img.active')
.fadeOut('fast')
.removeClass('active')
.css('opacity','0')
.addClass('hidden'),
nextimg = !cur.hasClass('last') ? cur.next('img') : cur.prev().prev().prev();
nextimg.removeClass('hidden')
.fadeIn('slow')
.css('opacity','1')
.addClass('active');
// Call the slider function again
slider();
},5000);
}
$('#someElement').click(function(){
// Clear the timeout
clearTimeout(timer);
});

Store the result of setInterval in a variable.
Then use clearInterval to stop it.

Store the value returned by setInterval, say intervalId to clear it, your click handler should look like this:
function stopSlider() {
//prevent changing image each 5s
clearInterval(intervalId);
//stop fading the current image
$('img.active').stop(true, true);
}

Related

request animation frame loop

I came across this code
https://gist.github.com/joelambert/1002116 and i thought of playing around with it
I tried to create a loop and stop it
var tick = 0;
var dor = requestInterval(function(){
tick++;
console.log("hi", tick)
if (tick > 10){
stop();
}
},300)
function stop(){
console.log("stop")
clearRequestInterval(dor);
}
But the clearRequestInterval is not clearing the timer. But when i tried to call it from a button's event handler its working. Am I missing something?
I have attached a codepen
http://codepen.io/srajagop/pen/KgbbpR
#Bergi is right that the example code you tried to use is broken, it doesn't support cancelling the interval timer from within the interval function itself. You can work around that by invoking the clearRequestInterval asynchronously:
function stop() {
console.log("stop");
window.setTimeout(function() {
clearRequestInterval(dor);
}, 0);
}
Or perhaps better, you could fix the example code not to reschedule itself even if it was cancelled from within the interval function.

How can I reset a settimeout

I tried the answer here: Resetting a setTimeout, but it doesn't seem to be working for me.
I'm building a catalog viewer using Owl Carousel. I have a function set to go off on the afterMove event handler that shows what page the user is on. It displays the page counter and then sets a timeout to have it fadeout after 1 second. Probably is lots of people go through pages faster than once per second. So, I need to reset the timeout if the function gets called again.
function showCounter(){
var $counter = $('#counter');
//clear timeout
window.clearTimeout(timeout);
//Display counter
$counter.show();
//set timeout
var timeout = window.setTimeout(function(){
$counter.fadeOut(500);
}, 1000);
}
But window.clearTimeout(timeout) doesn't seem to be working and I'm not sure why
Thanks
var timeout inside the function makes timeout local to the function; thus, every time you call showCounter, timeout is undefined. Move the variable declaration out of the function:
var timeout;
function showCounter() {
// ...
timeout = // NO VAR! ...
// ...
}

Ending a javascript function

I have an html page that links to a js file that has the following function:
function show360Simple( divContainerId, imageUrl )
The function gets called on an on-click:
<area onclick="show360Simple('pContainer5','images/porch1.jpg');">
And I want to know how to end the function with another on-click:
<div id="close-div" onclick="what is the syntax here to end the above function?"></div>
Its probably simple but I'm a novice and haven't been able to work it out yet - any help is greatly appreciated - cheers.
The script linked above is using setTimeout to manage the animation.
To stop, you will need to modify the code a bit and add a stop function.
The simplest approach would be to store off the timeoutId returned from each setTimeout call. Then, in the stop function, call clearTimeout passing in the stored timeoutId.
Without making too many changes:
// Declare a global timeoutId
var timeoutId;
In function show360 change the setTimeout call to:
timeoutId = setTimeout(…);
In function move360 change the setTimeout call to:
timeoutId = setTimeout(…);
Then add a stop360 function:
function stop360() {
clearTimeout(timeoutId);
}
Demo fiddle
This will stop the animation - basically freezing it. If you want to remove the changes made by the script you could change the stop function to something like this:
function stop360(divContainerId) {
clearTimeout(timeoutId);
if(divContainerId) {
var o = document.getElementById(divContainerId);
o.style.backgroundImage = '';
o.style.position = "";
o.innerHTML = "";
}
}
Demo with Clear

How to add .delay to .click on .each iteration (jquery)

So, I want to put delay on this JavaScript code.
$(function(){
$('.clickThis').each(function(){
$(this).click();
});
});
I tried this
$(function(){
$('.clickThis').each(function(){
$(this).click().delay(5000);
});
});
above script doesnt work .
Is there any alternative?
I've tried Google it but I still couldn't figure it out, because I have little knowledge in JavaScript.
This will do it:
$(function(){
$('.clickThis').each(function(i, that){
setTimeout(function(){
$(that).click();
}, 5000*i );
});
});
Here's a version using a recursive setTimeout loop.
$(function() {
var click = $('.clickThis').toArray();
(function next() {
$(click.shift()).click(); // take (and click) the first entry
if (click.length) { // and if there's more, do it again (later)
setTimeout(next, 5000);
}
})();
});
The advantage of this pattern over setTimeout(..., 5000 * i) or a setInterval call is that only a single timer event is ever queued at once.
In general, repeated calls to setTimeout are better than a single call to setInterval for a few reasons:
setInterval calls can queue up multiple events even if the browser isn't active, which then all fire as quickly as possibly when the browser becomes active again. Calling setTimeout recursively guarantees that the minimum time interval between events is honoured.
With setInterval you have to remember the timer handle so you can clear it
You need to write an asynchronous setTimeout loop, for more information http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/
Try to use this:
$(function () {
var items=$('.clickThis');
var length=items.length;
var i=0;
var clickInterval=setInterval(function(){
items.eq(i).click();
i++;
if(i==length)
clearInterval(clickInterval);
}, 5000);
});
var $clickthis=$(".clickthis");
var i= -1;
var delayed = setInterval(function(){
if (++i < $clickthis.length) $clickthis.eq(i).trigger("click");
else clearInterval(delayed);
}, 5000);
I am not sure but I think that setTimeout function should do the trick.
See here https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout
Try
$(function(){
$('.clickThis').each(function(_,i){
var me=$(this);
setTimeout(function(){me.click()},5000*i);
);
});

How to append data only one time after click with jQuery

So, i have this little function:
carousel_controls_buttons.live('click', function(e){
setTimeout(function(){
info_board_span.append(info_board_description);
e.preventDefault();
}, 450);
});
What i'm trying to do is stop appending info_board_description more then one time after two, three fast clicks. When i do this this data appends more than one time and i have content duplication. How can i stop this for some time, f.e. this 450ms? Thx for help.
Use a boolean to control it.
var flag = true;
carousel_controls_buttons.live('click', function(e){
e.preventDefault();
if (flag) {
setTimeout(function(){
info_board_span.append(info_board_description);
flag = true;
}, 450);
flag = false;
}
});
You can use clearTimeout function:
var t = '';
carousel_controls_buttons.live('click', function(e){
clearTimeout(t);
t = setTimeout(function(){
info_board_span.append(info_board_description);
e.preventDefault();
}, 450);
});
example: http://jsfiddle.net/xhSvC/
Note that live method is deprecated, you should use on method instead.
While the other answers ought to work, I would like to introduce you to the concept of debounce & throttle.
http://benalman.com/projects/jquery-throttle-debounce-plugin/ is one plugin you may use to achieve what you need, ie, ensure a function is executed only once per x seconds.
Throttle versus debounce
Both throttling and debouncing will rate-limit execution of a
function, but which is appropriate for a given situation?
Well, to put it simply: while throttling limits the execution of a
function to no more than once every delay milliseconds, debouncing
guarantees that the function will only ever be executed a single time
(given a specified threshhold).
carousel_controls_buttons.live('click', function(e) {
$.debounce(450, function() {
info_board_span.append(info_board_description);
e.preventDefault();
});
});
Put an count over there say var count=0; increment when hit and check for the condition if count==1 append it if not leave it
There is a one event for achieve this:
carousel_controls_buttons.one('click', function() {
setTimeout(function(){
info_board_span.append(info_board_description);
e.preventDefault();
}, 450);
});

Categories

Resources