1

I have made a timed function that delays for 9 second after the page loads before starting. However, I would like it to be cancelled if a user interacts with the div it is affecting. Here is my code for the function being called.

function buttonchange4(){
  $(".button4").css("backgroundColor","yellow").delay(3000).queue(function(next4){
  $(".button4").css("backgroundColor","silver");
     next4();
  });
};

var buttonshow3;
  $(document).ready(function(){
  $(".button4").delay(9200).queue(function(nextoooo){
      buttonchange4();
      buttonshow3 = setInterval( buttonchange4, 12000);
      nextoooo();
  });
});

And here is my code for stopping the function.

$('.button4').click(function(){
   $( ".button4" ).stop();
   clearInterval(buttonshow3);
   $('.button4').css("backgroundColor","yellow");
});

For some reason, after the delay of 3 seconds it still changes the background color of the button to silver... It seems to stop the delay function and jump straight to buttonchange4(); How can I stop this?

Huangism
  • 16,278
  • 7
  • 48
  • 74
user3362196
  • 102
  • 7

2 Answers2

2

return; breaks and stops the function

if you want to break the TimeInterval you can do it this way:

var i = setInterval(FunctionA, 1000);
clearInterval( i ); 

or you can stop the delay() with dequeue();:

$( ".button4" ).dequeue();
doniyor
  • 36,596
  • 57
  • 175
  • 260
  • I managed to clear the interval using the code above, but it would still run the buttonchange4() function once before ending it. – user3362196 Jul 31 '14 at 20:55
  • @user3362196 dont you need to ``dequeue();`` instead of ``stop()`` ? like ``$( ".button4" ).dequeue();`` – doniyor Jul 31 '14 at 20:58
  • Thank you! dequeue worked perfectly. I was using the wrong command to stop the function. – user3362196 Jul 31 '14 at 21:05
1

jQuery's delay function doesn't offer a way to cancel it (docs).

So I recommend using setTimeout and clearTimeout, like so:

var timeoutId = setTimeout(function() {
    // do something
}, 9000)
function cancel() {
    clearTimeout(timeoutId)
}
Jaime Gómez
  • 6,961
  • 3
  • 40
  • 41