1

I want that if a user clicks D a functions gets executes after one second and if a person clicks A before the code in timeout is executed, I want it to wait for the code to get executed. I dont know if this is possible with code I wrote. If it's possible please let me know how to do it. Any help will be highly appreciable. JQuery can be used too.

$(document).keydown(function (e) {
  // D click
  if (e.key === 'd' || e.key === 'D') {
    setTimeout(function () {
      console.log('d clicked')
    }, 1000)
  }
  // A click
  else if (e.key === 'a' || e.key === 'A') {
    console.log('a clicked')
  }
});

3
  • Set a global flag dIsRunning to true before the timeout. Set it to false within the timeout. Check if the flag is false before running anything else. Commented Jul 9, 2021 at 13:24
  • Actually I'm a bit new to javascript so I dont know much about it. Can you explain it with a code? Commented Jul 9, 2021 at 13:26
  • 2
    Does this answer your question? wait until condition is met or timeout is passed in javascript Commented Jul 9, 2021 at 13:31

1 Answer 1

1

You can use JavaScript promises to solve that problem. With them, it's possible to set a function to be executed right after another, that is, attaching callbacks, without polluting your code.

Read mode about promises here: Promise - JavaScript | MDN

In the code below, when 'a' is pressed, it verifies if there is a promise for 'd'. If so, it waits for the promise to be fulfilled, printing 'a clicked' to the console afterwards. If no, it prints the message at the same moment.

let d;

$(document).keydown(function (e) {
    // D click
    if (e.key === 'd' || e.key === 'D') {
        d = new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log('d clicked');
                resolve();
            }, 1000)
        });
    }
    // A click
    else if (e.key === 'a' || e.key === 'A') {
        if (d) {
            d.then(() => {
                console.log('a clicked');
                d = null;
            })
        } else {
            console.log('a clicked');
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

2 Comments

No need for the global d, which actually causes some issues. For example, rapidly press the D key a bunch of times. Note that, since d is reused, the number of times the "d clicked" message is logged does not match the number of times "D" was pressed.
I want to set a promise on A click too and want to wait for A click function to execute before executing the d click function. Can you please tell me how to do that?

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.