Reputation:
I'm making an image scroller that automatically advances the image every few seconds (10 seconds for the sake of debugging) or when the user clicks the image. My code (shown below) works, although I'd like to "reset" the 10 second counter if a manual (click) advancement of the image is done. How can I do this? I seem to be having no luck with clearInterval.
...
setInterval('gallery()',10000);
$("#gallery").click(function() {
clearInverval();// <--- not working
gallery();
});
…
I see others defining a variable as (in my case) setInterval('gallery()',10000);
but I couldn't get that to work either =/
PS I have limited knowledge of languages other than C
Upvotes: 0
Views: 10362
Reputation: 3485
I struggled to make a simple pause/continue handler when doing prototype based coding and did not want to use any external plugin because of this.
The code below is pretty self-explanatory and will hopefully save other coders time.
Non-functional example:
/** THIS DID NOT WORK
function Agent( name )
{
this.name = name;
this.intervalID = undefined; // THIS DID NOT WORK!!!
} // constructor
Agent.prototype.start = function( speed )
{
var self = this;
this.intervalID = setInterval( function(){ self.act(); }, speed );
}; // start
Agent.prototype.pause = function()
{
clearInterval( this.intervalID );
console.log( "pause" );
}; // pause
**/
Instead you have to do it like this:
var intervalID = undefined;
function Agent( name )
{
this.name = name;
} // constructor
Agent.prototype.start = function( speed )
{
var self = this;
intervalID = setInterval( function(){ self.act(); }, speed );
}; // start
Agent.prototype.pause = function()
{
clearInterval( intervalID );
console.log( "pause" );
}; // pause
Upvotes: 0
Reputation: 3355
You need to set the setInterval as a variable for this to work..
var interval = setInterval(gallery, 10000);
$('#gallery').click(function() {
clearInterval(interval);
});
Upvotes: 1
Reputation: 19697
May be you can do something like this:
var handle = setInterval(gallery,10000);
$("#gallery").click(function() {
clearInterval(handle);
/*
* your #gallery.click event-handler code here
*/
//finally, set automatic scrolling again
handle = setInterval(gallery,10000);
});
Upvotes: 3
Reputation: 700820
The setInterval
method returns a handle to the interval, which you use to stop it:
var handle = window.setInterval(gallery,10000);
$("#gallery").click(function() {
window.clearInterval(handle);
gallery();
});
Upvotes: 4