Run code only after the setTimeout executes

2

I want the code to run normally, but when timeout gets the code it will wait for it to proceed, type:

Normal code:

setTimeout(function(){ alert("Hello"); }, 3000); // OPA UM TIMEOUT
alert('continuando'); // só depois do timeout ele da o alert
    
asked by anonymous 03.04.2015 / 05:46

2 answers

5

As far as I know this is not possible, because setTimeout() works as a sort of thread , ie it is asynchronous. What you can do is add a new function and call it within the timeout, something like this:

function outraFuncao() {
  alert("Continuando"); // executou depois do timeout
}

setTimeout(function() {
  alert("Hello");
  outraFuncao();
}, 3000);

This approach to using a second function is valid and one of the simplest ways to resolve, note that it is indicated by W3Schools .

Another way would be to use a callback function, but I saw no need to point out a slightly more complex approach to solving something so simple. =)

    
03.04.2015 / 05:58
5

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>     

03.04.2015 / 06:51