How to delay propagation of events with jQuery
I want to display a note after the user submits the form, but before he leaves the page.
I am currently using this (code example provided):
$('form').submit(function(event) {
$('.note').show();
setTimeout(function() {
$('form').unbind().submit();
}, 2000);
return false;
});
It works, but it doesn't seem enjoyable. Is there any other way like a function $.delayPropagation(2000);
?
PS: the note covers the entire screen, so the user will not be able to send it again during this time.
source to share
This is a suitable way to delay the operation.
In fact, you can cancel the event first to stop multiple calls (you have a 2 second window that they can send again).
As a standard practice, you should only run jQuery selectors once (use temp var to store the result). Prefixes $
are also another standard for naming jQuery variables. This now means that the code below will 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
avoid blocking your browser immediately.
Notes:
- An alternative would be to use
Ajax
to post a form, then have a delay, then navigate to a new page -
setTimeout
is the most ubiquitous way to delay code execution.
Note. I just wanted to use the term ubiquitous
in the post :)
source to share