0

I have javascript function1 which calls another function2 my requirement is that function 1 should not wait for function 2 execution.

My function 2 calls ajax which makes process delayed which causes user to wait until my function2 returns. is there any i can return from function1 as soon as function1 calls function2 ?

3
  • Use setTimeout to call the function2, and the function would return. Commented Nov 22, 2014 at 10:28
  • 2
    Actually calling ajax doesn't make the process delay if you use the asynchronous version of it. Commented Nov 22, 2014 at 10:30
  • Can you provide your code? Commented Nov 22, 2014 at 10:34

1 Answer 1

3

You can do something like this:

function f()
{
 f1();
 console.log("I'm impatient, can't wait for f1");
}
function f1()
{
 setTimeout(function(){f2();},0);
}
function f2()
{
 // your function which takes a long time to run
 for(var i =0;i<10000000;i++);
 console.log("I'm f2 and I'm finally done!");
}
f();

How does this work?

When you call f1(), it has the setTimeout function. setTimeout sees the function and puts it on the event queue, and the statement is done. Program control returns to f() and "I'm impatient, can't wait for f1" is printed, and then when f2 is executed completely, "I'm f2 and I'm finally done!" is printed.

Sign up to request clarification or add additional context in comments.

3 Comments

Minor point, but it would be completely equivalent to say setTimeout(f2, 0).
@torazaburo: Yes, true. This is a legitimate way to achieve what OP wants, I wish people would comment and explain the downvote :)
Even though old post, it helped me solve my problem, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.