AnApprentice
AnApprentice

Reputation: 111080

jQuery - UI Dialog - looking for a smart solution for a timed close

I wrote the following:

// Called with setTimeout(magicDialogDelayedClose, 2500);
function magicDialogDelayedClose() {
    $(".ui-dialog").fadeOut(function() {
        dialog_general.dialog('close');
    }); 
}

The above is called with setTimeout when I show a notice dialog that I want to auto close in 2.5 secs.

The problem I'm noticing with this is that if the use Manually closes a dialog this timer still is running. If the user then opens a new dialog (which is very possible) the timer can then close that NEW dialog.

What's a smart way to handle this?j

Upvotes: 1

Views: 4359

Answers (3)

Michelle
Michelle

Reputation: 19

Another twist, busy so only tried it in FireFox, but it worked ...

$('#dialogBox').html("Put some text message here.").dialog("open").delay(2500).fadeOut(function(){ $(this).dialog("close") });

Upvotes: 1

Marcus Whybrow
Marcus Whybrow

Reputation: 20008

You can clear a timeout (stop it from firing) by storing it in a variable and then using the clearTimeout() method:

var timeout = setTimeout(magicDialogDelayedClose, 200);
clearTimeout(timeout);

So if someone manually closes your dialog then stop the timeout from carrying on there and then.

A safe way to clear the timeout would be to determine whether timeout is not null before doing so:

function safeClearTimeout(timeout) {
    if (timeout != null)
        clearTimeout(timeout);
}

Upvotes: 1

Steven
Steven

Reputation: 18024

Coarsely speaking, in your situation, you don't want to have a function that applies globally. You want to queue a close on each dialog as it appears. As of version 1.4, jQuery has implemented the delay function that accomplishes just this. It adds a null action to the animation queue, so that subsequent chained animation functions come after the delay in the queue.

It would be implemented as follows:

function insertDialog() {
  // substitute your insertion code here
  var d = $('<div class="ui-dialog"></div>').appendTo($('#dialog_area'));

  // add a 2.5s delay into the animation queue, then add
  // a fadeOut with $(this).close() as a callback
  d.delay(2500).fadeOut(function(){ $(this).close() });
}

Upvotes: 4

Related Questions