Reputation: 335
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')
}
});
Upvotes: 1
Views: 200
Reputation:
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>
Upvotes: 1