2

am using below jquery for change image in every 1 second

window.setInterval(function(){ imagechanger(); }, 5000);

as automatic changer its working fine. now i need to add next button. I call the same imagechanger() function on the next button click. That is also working fine

$('body').on('click','#next',function(){
    imagechanger();     
 });

But suppose after calling the first change and waiting 4 seconds then i press the next button, when i click the button image is changing but the very next second another change call also triggered.

So how can i reset the time ??

Nith
  • 734
  • 4
  • 9

2 Answers2

5

To reset an interval you need to store it to a variable then call clearInterval on it before creating the new one. Try this:

// on load
var interval = setInterval(imagechanger, 5000);

$('body').on('click', '#next', function() {
    clearInterval(interval); // clear current interval
    imagechanger(); // call instantly
    interval = setInterval(imagechanger, 5000); // create new interval   
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

My solution was to make a simple Timer object and have it handle the interval.

http://jsfiddle.net/fk5cnvc2/

var Timer = function (interval) {
    var me = this;
    var timeout = null;

    me.interval = interval;

    me.tick = function () {};

    me.reset = function () {
        if (timeout != null) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function () {
            me.tick();
            timeout = null;
            me.reset();
        }, me.interval);
    }

    me.start = function () {
        me.reset();
    }

    me.stop = function () {
        clearTimeout(timeout);
    }
}

    function addResult() {
        $('#results').append("<div>Tick!</div>");
    }

var myTimer = new Timer(5000);
myTimer.tick = addResult;

$('#button').on('click', function() {
    addResult();
    myTimer.reset();
});

myTimer.start();
Michael Coxon
  • 5,311
  • 1
  • 24
  • 51