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')
  }
});
Ghayas Ud Din
  • 315
  • 2
  • 14
  • 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. – Heretic Monkey Jul 09 '21 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? – Ghayas Ud Din Jul 09 '21 at 13:26
  • 2
    Does this answer your question? [wait until condition is met or timeout is passed in javascript](https://stackoverflow.com/questions/49054748/wait-until-condition-is-met-or-timeout-is-passed-in-javascript) – Heretic Monkey Jul 09 '21 at 13:31

1 Answers1

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>
  • 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. – benbotto Jul 09 '21 at 14:12
  • 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? – Ghayas Ud Din Jul 12 '21 at 04:38