Run code only after setTimeout runs

Asked

Viewed 2,350 times

2

I want the code to run normally, but when the timeout get the code will wait it perform to proceed, like:

Normal code:

setTimeout(function(){ alert("Hello"); }, 3000); // OPA UM TIMEOUT
alert('continuando'); // só depois do timeout ele da o alert
  • 1

    This may help you to understand: http://answall.com/a/45721/3635

  • 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.

2 answers

5

As far as I know that’s not possible, because the setTimeout() works as a kind of thread, that is, 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 in using a second function is valid and one of the simplest ways to solve, note that it is indicated by W3schools.

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

  • 1

    the code I showed in the question is just an example, in my original code it is already inside a function that could not call another because of the context of everything, this callback how would work? Thank you!

  • So, if you already have the function, you could call it quietly. Any special reason not to do it that way? About callback setTimeout() already uses one, when you declare "setTimeout(Function() {", this anonymous function is a callback. Anything put part of your original code so we can try to help.

  • 2

    +1 Just one comment on this "works as a kind of thread": although in fact this code is asynchronous, it will run on thread leading. This means that - just like all the code on the page - as long as it is running nothing else will run (this is evident if you delay closing the alert, note that nothing else happens in the meantime, even if you own more than one setTimeout and their interval has already expired).

  • Well remembered @mgibsonbr. =)

  • Well look at my problem: I have an X function that is able to read and process a data stream. In this function I execute a function of a Library called Dexie (I posted her question until) However the answer of this library takes 3s to arrive and without this answer the code below it will probably work irregularly, understand? and it is my code that needs to be gathered.

  • @mgibsonbr has no way to 'fix'? for him to pause the code? :/

  • @Elaine, about callbacks, there’s a very good article I read a while back, you can access it here. But try to solve by calling the function, seems to be the most quiet way to do.

  • I understood yes. I caught a similar problem, where I had an ajax that took some time to process the customer’s order. I decided by blocking the screen controls and adding a progress bar for the client, so it does not get the sense of screen locked. And the progress bar can be up to a GIF, with a circle rotating and a text "Processing...". Wouldn’t that be another alternative?

  • not because the code would be executed. would have to follow the same order even..

  • There’s another way to handle it. Do the following, declare a variable "flag = false", then you use a while that waits for this flag to be true, which will be set to true setTimeout(). Could you get the idea? Something +- thus.

  • 1

    @silvioprog If this is done, the setTimeout will never be called... P

  • So @mgibsonbr, only she calls the setTimeout() before that Sleep Which she’s trying to do, so it might actually work. I needed to do a test here, but there’s a good chance it’ll work, as they explained at that link ...

  • @silvioprog I guarantee you it doesn’t work! This link is a lousy practice, don’t use. In this case it works, but only because within the loop the condition is changed to exit the loop (if it did not change, it would enter an infinite loop; see my example above - it will seem that the browser stuck, wait about 20s).

  • 2

    @mgibsonbr I saw there, boy, if Elaine use this approach she will be entering the territory of the gambiarra rs... But here’s a tip for another programmer not to fall into a trap like this. I believe it’s worth it to take some time and try to refactor the code, to finally call it that way we explained it to her. Make an effort there Elaine. =)

Show 9 more comments

5


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.