restarting a setInterval - javascript

So I have a timer rotates a set of images ever 5 seconds. Therefore, I am running this upon document launch.
$(document).ready(function() {
var intervalID=setInterval(function(){
rotate();
}, 5000);
});
The Rotate function simply just rotates the images. However, I also allow the user to manually select what image they are looking at. Because of this I need to cancel the SetInterval and then start it over back at 5 seconds again
What I am trying to do is cancel the interval then start it over by doing this
$('a').click(function(){
clearInterval(intervalID);
intervalID=setInterval(function(){
rotate();
}, 5000);
});
However, the code doesn't seem to reset the interval like I had hoped.

If the intervalID variable is declared within the .ready() scope, the following ought to work (untested):
$(document).ready(function() {
var rotate = function() { ... },
intervalID = setInterval(rotate, 5000);
$('a').click(function() {
clearInterval(intervalID);
intervalID = setInterval(rotate, 5000);
});
});

Just make intervalID be global variable by declaring it outside and above all functions.
With your current code its scope is limited to $(document).ready() method so it might cause the problem you describe.

Well, it looks like you are declaring interverID locally within the anonymous function from your .ready() handler. I'm actually wondering why you don't face a Reference error in your click-event handler, since intervalID cannot be known there.
You need to make sure that this variable is available and does have a shared context for both functions. Easiest way to go, create an anonymous self invoking method around your script and declare that variable out of scope.
(function _myPrivateContext($, window, document, undefined) {
var intervalID = null;
$(document).ready(function() {
intervalID = setInterval(rotate, 5000);
});
$('a').click(function(){
clearInterval(intervalID);
intervalID = setInterval(rotate, 5000);
});
}(jQuery, window, document));

Related

fire a function after window resize

I'm doing a few functions on $(window).resize(). One of the functions inside it, is a complex animation with lots of divs.
$window.resize(function() {
// some functions
doAnim();
}
the problem here is, that the resize() function triggers a lot. Is it possible to fire one function after the resize() is finished, that it doesnt fire a hundred times?
Cheers
So, I believe this is a similar scenario when a user "type" something: you can't know when the user finished to compose a sentence, the same here, you don't know when the user has finished to resize; so what you can do is have an acceptable interval:
var idt;
$(window).resize(function() {
if (idt) clearTimeout(idt);
idt = setTimeout(doAnim, 500);
}
You can also use a closure to avoid to pollute the global scope with idt variable.
However the main point here is that every time the user resize the window, it set a timeout and clear the previous one: the doAnim function will be executed only if the user leave the window without resizing it for half second. Of course you can set your own delay.
You can achieve it as shown below. This will call when you finish with resizing :
var myTimer;
$(window).resize(function()
{
// some functions
var interval = 500;
clearInterval(myTimer);
myTimer = setInterval(function () { doAnim(); }, interval);
});
function doAnim()
{
clearInterval(myTimer);
alert('Resized');
}

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);
);
});

Stopping a running function in javascript/jquery on click event

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);
}

Problems getting a jQuery .mouseenter()/.mouseleave() script with user interaction to work

Firstly, apologies for the title, I could not think of a suitable one.
I am unsure as to why the hide() function within the below code comes back erroneous in firebug when triggered, I am pretty sure the rest of the code will work fine once I have ironed this flaw out, any help/suggestions would be appreciated.
Firebug Console error:
hide is not defined
it-services() it-services (line 396)
time = setTimeout("hide()",3000);
Code I have thus far:
var time;
$("#form").mouseenter(function() {
clearTimeout(time);
$(this).delay(800).animate({
right: 0
}, 2000);
}).mouseleave(function() {
function hide() {
$(this).delay(800).animate({
right: "-325px"
}, 1000);
}
time = setTimeout(hide,3000);
});
Thank you all very much for any help in advance,
Dan.
You're declaring the hide() function after you invoke it using setTimeout. Simply put the declaration before the setTimeout call.
Also, when you pass a string of code as first argument to setTimeout, it gets evaled. eval is evil. Just pass the function object:
function hide() {
$(this).delay(800).animate({
right: "-325px"
}, 1000);
}
time = setTimeout(hide, 3000);
There are 2 issues in the new code
Inside the hide function, the context of $(this) is not same as the
when it is being called inside the mouseout function.
Secondly, the hide function is defined as an anonymous function inside the mouseout function
I feel it would make more sense if it were a function declared outside the mouseover event handling function. That way you can globally reference it from the setTimeOut as well as the mouseout event handler. Try the below code. I believe this should solve the issue, or at least take you a step ahead.
var time;
var $form;
$("#form").mouseenter(function() {
$form = $(this);
clearTimeout(time);
$(this).delay(800).animate({
right: 0
}, 2000);
}).mouseleave(function() {
hide();
time = setTimeout(hide,1000);
});
function hide() {
$form.delay(800).animate({
right: "-325px"
}, 3000);
}

clearTimeout not working in javascript autocomplete script

I am using the following code as part of an autocomplete script to avoid hammering the server with every keystroke:
var that = this;
textInput.bind("keyup", function() {
clearTimeout(that.timer);
that.timer = setTimeout (that.doStuff(), 2000);
});
Unfortunately, this does not clear the old timers. They still all execute.
Does anyone know what I'm missing?
Thanks!
You probably want to use:
that.timer = setTimeout (that.doStuff, 2000);
instead of:
that.timer = setTimeout (that.doStuff(), 2000);
Otherwise, doStuff will be called immediately.

Categories

Resources