If you have an extensive function - either at the top-level or another function - and you want an excerpt from it to run only after a second condition is satisfied (a certain time has elapsed, a call ajax has completed, etc.), it is necessary to split it into two or more smaller functions. As the JavaScript context in a browser is essentially single-threaded , you can not "pause" the execution for a certain time, otherwise the entire page would be " / p>
That is, if you have a code like this:
blá
blá
blá
função assíncrona
blá
blá
blá
You should turn it into something like this:
blá
blá
blá
função assíncrona com callback "meuCallbak"
function meuCallback() {
blá
blá
blá
}
For an example with setTimeout
, see silvioprog's answer . For an example with, say, ajax via jQuery:
blá
blá
blá
$.ajax(...).done(function() {
// Só vai executar depois que a chamada ajax tiver retornado com sucesso
blá
blá
blá
});
Etc. If you want certain elements in the interface to be inaccessible while this asynchronous action does not complete, you must disable them before firing this action (the first group of "blasts") and enable them again after the end of this action (the second group of "blasts").
By the way, if as I said in comment a "delay in 3s to arrive" response, that does not mean that a% of 3s% would be correct - because when it takes longer, how does it stay? Ideally, you should use the callback functions of your API (if it is asynchronous, you probably have it somewhere, just find it) and give it that code that has to be executed later. p>