Hi All,
First time posting here!
I have the JS code below. I also have an HTML code that has a button that uses this JS code and calls roll() function. I want the button to be doing nothing until roll function is executed fully in case the button was hit multiple times. So I added the pending variable which is set to false and turns to true once the function starts executing and turns back to false once it finishes executing.
But what I am seeing is the pending value turned back to false before the function finishes executing. How do I solve that? I thought functions were executed sequentially.
var pending = false;
var position = 16;
function roll() {
if (pending == false) {
pending = true;
if (position == 16) {setTimeout(function(){document.getElementById(position.toString()).appendChild(elem);}, 5000);}
pending = false;
}
else {return;}
}
The execution will continue passed setTimeout and then when it is ready it will run. Even if you have 0 delay.
/* first run this */
let number = 0;
setTimeout(() => {
number = 10
}, 0)
console.log(number);
// 0
number = 42;
console.log(number);
// 42
/* now run this */
console.log(number);
// 10
You can disable the button using the disabled attribute. Why do you need setTimeout?
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
Note: Backticks are not single quotes.

you would have put pending false inside the timeout like so
var pending = false
function roll() {
if (!pending) {
console.log('clicked')
pending = true
setTimeout(() => {
console.log('finished')
pending = false
}, 5000)
}
}
Thanks for the response. I need the setTimeout function to be able to space out events on a simple web game I am making. Basically I have a function roll() executed by a button which rolls a die. But once the die is rolled it will put out a message saying the number rolled. I wanted 5 second delay between this message and the actual movement of a card on the board. The card would move by, say, 2 blocks if we rolled 2.
For disabling the button the disabled function works great! As for delaying execution I put the event to enable the button again inside the delay function as biscuitmanz recommended and it works great. Thanks again.
Thanks man. That solved the execution issue. I also used the disabled function to disable the button which was more efficient. Thanks.
1 Like