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?

4
  • 6
    By using return. Commented Jul 31, 2014 at 20:47
  • 1
    I think it's the setInterval the problem ... try to clear the setInterval like here Commented Jul 31, 2014 at 20:50
  • Why do you have a delay AND a setInterval? Nested no less. Commented Jul 31, 2014 at 20:50
  • I need it to run every 12 seconds, starting 9 seconds after the page is loaded Commented Jul 31, 2014 at 20:59

2 Answers 2

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(); 
Sign up to request clarification or add additional context in comments.

3 Comments

I managed to clear the interval using the code above, but it would still run the buttonchange4() function once before ending it.
@user3362196 dont you need to dequeue(); instead of stop() ? like $( ".button4" ).dequeue();
Thank you! dequeue worked perfectly. I was using the wrong command to stop the function.
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) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.