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?

Ex-iT
  • 1,479
  • 2
  • 12
  • 20
Poles
  • 3,585
  • 9
  • 43
  • 91

3 Answers3

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.

Mitya
  • 33,629
  • 9
  • 60
  • 107
  • how can I get the prompted value using setTimeout function?? – Poles Mar 24 '14 at 10:45
  • 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. – Mitya Mar 24 '14 at 10:46
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

Community
  • 1
  • 1
ajimenez
  • 175
  • 2
  • 14
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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • ok got it...but how do I store the `label` value in a variable? – Poles Mar 24 '14 at 10:59
  • You need to change your approach completely. It doesn't make sense to store it in variable if you have async code. Use callbacks. – dfsq Mar 24 '14 at 11:00