Define maximum wait time during "do... while" loop?

Find out why the . goes before the /

Moderator: Paul Tuersley

Post Reply
thifcosta
Posts: 3
Joined: October 31st, 2017, 12:25 pm

February 25th, 2019, 1:01 pm

Hi!

I'm writing a script that needs user interaction to define what the next step is going to be. For that, I wrote a do..while loop that expects a keyboard input. So in the example below, you have to run the script and then press the key "1" or "2" and the script will alert the key name. It is working perfectly, as it follows:

Code: Select all

var keyPress = false;
var whatToAlert = "No keys were pressed";

do {
    var kN = ScriptUI.environment.keyboardState.keyName;
    switch(kN){
        
        case "1":
        whatToAlert = "You pressed the key \"1\"";
        keyPress=true;
        break;
        
        case "2":
        whatToAlert = "You pressed the key \"2\"";
        keyPress=true;
        break;
        
    }
} while (keyPress == false);

alert(whatToAlert);

The script is useful as it is, but if the user do not press any key, he will be stuck forever inside the loop. That is why I wanted to add a "time out" function, for the script to stop running if the user did not press any of the two keys for 2 seconds. But I can't figure out how to do it. I tried adding $.sleep(2000) to the "while" part of the code, but this would make the script wait for 2 seconds even if the user presses one of those keys... So I just run out of things to try...

If anyone could help would be awesome!
Thank you in advance!
thifcosta
Posts: 3
Joined: October 31st, 2017, 12:25 pm

February 25th, 2019, 5:00 pm

I had posted the same question on creative cow and got an answer from Oleg Pirogov, that worked exactly as I was expecting...

He said:
"How about setting var start = Date.now() before loop and adding && (Date.now()-start < 2000) to while?"

the code ended up like this:

Code: Select all

var keyPress = false;
var whatToAlert = "No keys were pressed";
var start = Date.now();

do {
    var kN = ScriptUI.environment.keyboardState.keyName;
    switch(kN){
        
        case "1":
        whatToAlert = "You pressed the key \"1\"";
        keyPress=true;
        break;
        
        case "2":
        whatToAlert = "You pressed the key \"2\"";
        keyPress=true;
        break;
        
    }
} while ((keyPress == false) && (Date.now()-start < 2000));

alert(whatToAlert);
If anyone is interested on checking out the thread:
https://forums.creativecow.net/thread/2/1135196

Thanks!
Post Reply