If you have an extensive function - be on top-level or in another function - and whether an excerpt of it only runs after a second condition is satisfied (some time has passed, an ajax call has completed, etc.), it is necessary to divide it into two or more minor functions. Like the Javascript context in a browser is essentially single-threaded, you cannot "pause" the execution for a certain time, otherwise the whole page would be "locked".
I mean, if you have a code like this,:
blá
blá
blá
função assíncrona
blá
blá
blá
You must 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 the response of the silvioprog. 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 that action (the first group of "blah") and enable them again after the end of that action (the second group of "blah").
By the way, if as was said in comment a response "takes on average 3s to arrive", it does not mean that a setTimeout
of 3s would be correct - because and when it takes longer, how does it look? The ideal would be to use the functions of callback of your API (if it’s asynchronous, you definitely have it somewhere, just find it) and pass to it this code that has to be executed later.
This may help you to understand: http://answall.com/a/45721/3635
– Guilherme Nascimento
I suggest [Edit] your question by asking more context. This is a XY problem: you’re asking about your attempt to resolve, and not about the real problem that you are facing. If the root of your problem is another, mention this in the question, so you can receive better answers.
– mgibsonbr