1

Event listeners actually begin to run their code before the event is finished, hence we have the ability to preventDefault(). But what if I have to do something only after the event is finished and it's really important not to do that earlier?

I've tried placing the code that needs to be run only after the event is finished after the listener's return statement like a self-invoking function:

$(...).on(event, function(evt){
    //do stuff
    return (function(){
        // do stuff after the event
        })();
});

But that wasn't helpful. The only thing that seems to work is using setTimeout. But it's really not a good idea, because it's not deterministic and under certain conditions the timeout may turn out to be insufficient and the idea fails. How can I do something only after the event is already finished?

tristantzara
  • 5,597
  • 6
  • 26
  • 40
  • What is `//do stuff` within event handler ? What is method of determining _"after the event is already finished"_ ? Can create stacksnippets , jsfiddle http://jsfiddle.net to demonstrate ? – guest271314 Jul 12 '15 at 14:30
  • @vinayakj _"use $.when as mentioned on above questions' answer"_ If function passed to `$.when()` is not a jQuery deferred object would run immediately ? – guest271314 Jul 12 '15 at 14:35
  • @vinayakj and how do I link it to one of the pre-defined events? Like do something after form is submitted? – tristantzara Jul 12 '15 at 14:36
  • @TristanTzara _" Like do something after form is submitted?"_ Is `event` `form` submission ? – guest271314 Jul 12 '15 at 14:49
  • @guest271314 doesn't matter. Consider any event. If you wanted to tell me that I have to use ajax ready state in that case — I know. But the situation is slightly different, so I must use event handlers. – tristantzara Jul 12 '15 at 17:12
  • What is `//do stuff` within event handler ? What should be run after `//do stuff` is completed ? _"But the situation is slightly different"_ What is _"the situation"_ in `js` ? – guest271314 Jul 12 '15 at 17:19

1 Answers1

0

An event handler is invoked slightly prior as a browser optimization to prevent possible blocking behavior. You may use setTimeout to give it a bit slight delay of, say 30ms. The invoking and handling of an event by definition is Not deterministic. It does not know what it means by "finishing" an event. What you do with the handler has more context. If it's an XHR call, there is the onreadystatechange callback, if it's loading an image, use the "onload" event. Form submission, if done by an AJAX call, can be detected by readyState==4; otherwise you may detect the $_POST data on the server side and inject a script block.

Schien
  • 3,855
  • 1
  • 16
  • 29