简体   繁体   中英

Timing an if-statement in JavaScript

My idea is to build a program that is completely timed and runs on it own, without any input from the user. However I want to use if-statements in the form of:

if(height()>10){ do something }

height() itself is a function and does something as well. call() is just another function that has to be invoked but is also timed with setTimeout . I want the return to be invoked after everything in call() is executed. However

function () height() {call(); setTimeout(function() { return client._lastAltitude;},1000);}

does not return the proper value or does not work the way I thought it would. Is it possible to time a return statement so that the if-statement is halted?

--Trying to clarify it now and giving my main code: I do this because I want to give a drone a flypath. I use setTimeout calls to send the move orders and certain timepoints. Because of this I also want to use if-statements that get called at a certain time. However as Javascript is asynchron the usual behaviour would be to instantly run the if-statement as it waits for time to pass to invoke the other functions. But the functions might alter the result of the if-statement. Because of this I want the return of height() to be returned after all the functions are invoked and done. Main code looks like this right now:

function altitude(){
    fullFlight.push("Height");
    runList.forEach(function (aufruf){
        aufruf(); });
        client.after(1, function () {
            emptyLists();
            });
function height() {
        altitude();
    client.after(2, function() { return client._lastAltitude});
}

But the return statement of height() does not work as intended. after() is like setTimeout just with incrementing offset.

You can do this without setTimeout()

function call() {
  console.log('call called');
}

function height() {
  let start = new Date().getTime();
  call();
  while (new Date().getTime() < start + 1000) {}
  return client._lastAltitude;
}

if ( height() > 10 ) {
  console.log('done');
}

Edit: Note that this will halt your program until height is finished executing. If that's not what you want, you could look at promises as gforce301 suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM