Search code examples
javascriptjquerydelayevent-propagation

How to delay event propagation using jQuery


I want to display a note after the user submits a form but before he leaves the page.

Currently I'm using this (reduced example code):

$('form').submit(function(event) {
    $('.note').show();

    setTimeout(function() {                 
        $('form').unbind().submit();
    }, 2000);

    return false;
});

This works but doesn't seem to be nice. Is there any other way, like a function $.delayPropagation(2000);?

PS: The note covers the whole screen, so the user won't be able to submit again during this time.


Solution

  • That is an appropriate way to delay the operation.

    You may actually want to unbind the event first to stop multiple calls (you currently have a 2 second window in which they could submit again).

    As a standard practice, you should only run your jQuery selectors once (use a temp var to hold the result). $ prefixes are also another standard for naming jQuery variables. This now means the code below would support multiple forms on a page separately.

    $('form').submit(function(event) {
        var $form = $(this);
        $('.note').show();
        $form.unbind()
        setTimeout(function() {                 
            $form.submit();
        }, 2000);
    
        return false;
    });
    

    You must return false immediately to avoid blocking the browser.

    Notes:

    • An alternative would be to use Ajax for the form post, then have the delay, then goto a new page
    • setTimeout is the most ubiquitous way to delay code from executing.

    Note: I just wanted to use the term ubiquitous in a post :)