This is a pretty advanced topic! I highly recommend you read about Promises and async/await. Being experienced with asynchronous programming and JavaScript in general will also really help.
In the future you'll be able to use async/await to write this pretty much the same as you did:
function wait() {
return new Promise(function(resolve) {
setTimeout(resolve, 100)
});
}
async function close() {
var closed = 1;
var opened = 19;
var gate = opened;
while (gate !== closed) {
gate -= 1;
gateEl.style.paddingTop = open + '%';
await wait();
}
}
This has a few different parts to it, so I'll go over each..
First, I fixed a couple of general issues with your code:
gate.style.paddingTop = open'%';
// changed to:
gateEl.style.paddingTop = open + '%';
// First, we need to join the open variable and the '%' string, so
// I add a + for that; second, gate is a number, not a DOM element,
// so I assumed there is a new variable called "gateEl" that means
// the actual element. Supply that in the actual code.
Then I implemented async/await into the code. This involved a few changes. I redefined the function wait:
function wait() {
return new Promise(function(resolve) {
setTimeout(resolve, 100)
});
}
It looks kind of confusing but basically I'm making a new Promise object given a function argument. Promises are the things that make async/await work. In my wait function, when await wait() is called, resolve is called 100 milliseconds later. resolve is what says that the code after await wait() can run.
Next, I added async before function close() {...} -- that makes await work inside of it.
Finally, I replaced wait() with await wait(). This changes your browser from thinking "call the wait function" to "call the wait function, and then wait until the promise actually the then-able object it returns to resolve." And we know that the promise resolves 100ms after wait is called - because we defined it to do so.
The nice thing about await fn() is that loops and other control structures work really well with it.
setTimeout()works. It takes two arguments, and the first one is the function to call when the timer expires. It is not a "sleep" function.gate.style.paddingTop = open'%';.gateis a Numeric, sogate.styleisundefined.open'%'which I think you probably mean to beopen + '%'but I'm guessing, and it's not clear what you're trying to do withgate.style.while (gate !== closed) {. This appears to be an infinite loop in your case.