0
var label = prompt('Label for Vertical Line');

This code returns the value in label which I enter in the prompted field. But I want some time delay to get the prompted value.

I'm using this code:

var label=alertWithoutNotice();
function alertWithoutNotice(){
    var lab;
    setTimeout(function(){
        lab=prompt('Label for Vertical Line');
    }, 1200);
    return lab;
}

But this doesn't return any value. Please tell me what is wrong?

3
  • the function is executed by setTimeout after lab has been returned Commented Mar 24, 2014 at 10:40
  • so what should I do?can you give me the proper code? Commented Mar 24, 2014 at 10:43
  • you need to chain the behavior that uses lab into the end of the function given to setTimeout Commented Mar 24, 2014 at 10:45

3 Answers 3

0

This is a chronological issue. setTimeout schedules an asynchronous event. That means, until it runs, the rest of your script will continue to execute.

The result is your return lab line is executed before the timeout callback fires. And so on the return, lab is undefined at that point.

As such, you can't return values from asynchronous events, or at least not meaningfully.

Something like jQuery's deferred objects would be your best route to a fix here, but I don't know if jQuery is an option for you.

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

2 Comments

how can I get the prompted value using setTimeout function??
Well you already ARE getting it; it's just you can't return from it, for the reasons I said. There is no easy fix with the pattern you currently have; your script will continue to run but without a value for lab, because it doesn't have one until the callback fires.
0

The problem is that you are returning value before get inside timeout because setTimeout function is asynchronous.

Take a look here to use synchronously: using setTimeout synchronously in JavaScript

Comments

0

Since you are dialing with asynchronous operation the simplest approach here is to use a callback function. For example:

alertWithoutNotice(function(label) {
    alert(label)
});

function alertWithoutNotice(callback) {
    setTimeout(function() {
        callback(prompt('Label for Vertical Line'));
    }, 1200);
}

So think of it is that alertWithoutNotice is notified when label is available. When it happens callback is invoked.

2 Comments

ok got it...but how do I store the label value in a variable?
You need to change your approach completely. It doesn't make sense to store it in variable if you have async code. Use callbacks.

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.