DNB5brims
DNB5brims

Reputation: 30578

How to tell JS to wait...?

I know there is a method like this :

setTimeout("functionA();",1250);

That can delay my process, but the problem is , the functionA have some value to return. When I use this way, it is not get me back the functionA return value:

this.sth = setTimeout("functionA();",1250);

I means, this.sth is not the result I want.

Upvotes: 0

Views: 719

Answers (4)

SpliFF
SpliFF

Reputation: 38976

i've seen solutions to this using for loops with thousands/millions of iterations. However be warned this can make the browser unresponsive if used incorrectly.

Upvotes: 0

Jeremy Wall
Jeremy Wall

Reputation: 25237

setTimeout is an asynchronous operation. This means that functionA gets run after the timeout but the rest of the script keeps running. It's a common mistake new javascript programmers make to think the script will be pausing when causing this.

If you goal is to make the script pause your better off using a while loop or for loop with dates. This is probably a bad idea though. A scrip that pauses can do weird things to browsers including making the whole browser pause while it runs. That includes all the tabs. This is probably not what you want. The better bet is to do like Garret mentioned and make it so that the operation works asynchronously but still accomplishes what you wanted.

Upvotes: 0

marcc
marcc

Reputation: 12399

You could do:

setTimeout(functionA(functionB()), 1250);

and define functionB as:

function functionB(resultFromA) {
}

and functionA would look like:

functionA(callback) {
    // do something useful
    callback(result);
}

Upvotes: 0

Garrett
Garrett

Reputation: 8070

You should make a functionB() that does this:

function functionB() {
    this.sth = functionA();
    // do things with the returned value
}

Upvotes: 1

Related Questions