user3362196
user3362196

Reputation: 102

How can I stop a function early?

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?

Upvotes: 1

Views: 118

Answers (2)

doniyor
doniyor

Reputation: 37846

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

Upvotes: 2

Jaime Gomez
Jaime Gomez

Reputation: 7067

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

Upvotes: 1

Related Questions