Mr. MikaS Mr. MikaS - 7 months ago 14
Javascript Question

Java script function error

I want the

close
and function to modify the variable
gate
, by making the padding bigger until it equals the variable
open
. I don't know why it won't work, please help.

function wait() {
setTimeout(100);
}

function close() {
var closed = 1;
var opened = 19;
var gate = opened;

while (gate !== closed) {
gate-=1;
gate.style.paddingTop = open'%';
wait();
}
}

Answer

Timeouts in JS are not blocking - thing of them as running in a separate thread. There are tons of resources about how they exactly work online, so I won't get into that.

To fix your code, you can refactor is to make recursive calls:

var closed = 1;
var opened = 19;
var gate = opened;
var gateEl = document.getElementById('gate');

function close() {
    if (gate !== closed) {
        gate -= 1;
        gateEl.style.paddingTop = gate + '%'; // open stays the same
        setTimeout(close, 100);
    }
}
  • make recursive calls to your close function
  • define an element which will have its padding changed
  • use gate instead of open to actually change the padding

Here's a live example:

var closed = 1;
var opened = 19;
var gate = opened;
var gateDiv = document.getElementById('gate');

function close() {
  console.log(gate);
  if (gate > closed) {
    gate -= 1;
    gateDiv.style.paddingTop = gate + '%';
    setTimeout(close, 100);
  }
}

close();
#gate {
  height: 50px;
  width: 50px;
  background: green;
}
<div id="gate"></div>

Comments