6

Possible Duplicate:
.delay() and .setTimeout()

Is there a way to break and stop javascript delay here ?

I want user when click on button this delay will stop and not execute the expected code like here

  $(#my_id).html('write my string here').delay(12000).fadeOut(1000) ;

so how can this be stopped to not fadeOut my string when user click on button with id 'my_button' ? any help is much appreciated

Community
  • 1
  • 1

2 Answers2

5

As documentation for jQuery.delay clearly states, you can't cancel delay configured using that function.

[...] Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases [...]

Use regular javascript setTimeout to achive easily cancellable actions. For example your code could be transformed into:

$("#my_id").html('write my string here');
var myTimeoutId = setTimeout(function() {
    $("#my_id").fadeOut(1000);
}, 12000);

// to somewhere else cancel that timeout use clearTimeout function like so:
clearTimeout(myTimeoutId);
WTK
  • 16,583
  • 6
  • 35
  • 45
  • Delay is handled by setTimeout function. fadeOut will be issued after 12000 miliseconds, just as that would be when using jQuery.delay function. – WTK Dec 12 '12 at 14:39
  • ok seems settimeout will work when its cancellabe. thx –  Dec 12 '12 at 14:44
1

Apparently not, if you check out the documention. It is suggested that setTimeout could be an alternative to what you need.

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

musefan
  • 47,875
  • 21
  • 135
  • 185