Home > Enterprise >  Function inside loop wont run
Function inside loop wont run

Time:08-16

I've been bashing my head against this wall I am completely new to JavaScript coming from c# and I am completely baffled for my class I have to smooth out a simple code we made to count down from zero by making it into a loop and for the life of me I just cant get it to work

var i = 10;
var timeout = 10000;
var x = 10
if (i == 5) {
  alert("help me")
}

while (i > 0) {
  //10
  setTimeout(() => {
    document.getElementById("counter").innerHTML = i;
    i = i - 1;
  }, timeout);
  timeout = timeout - 1000;
}

CodePudding user response:

setInterval is what you're looking for to execute a function every certain amount of time:

let i = 10;
let interval = setInterval(function() {
    document.getElementById("counter").innerHTML = i;
    i--;
    if(i < 0) clearInterval(interval);//Clear the interval when complete
}, 1000);//Every 1000 ms = every second

CodePudding user response:

Asynchrony in JavaScript is a rather involved subject.

Traditional loops (for, while, do..while, for..of) are not aware of asynchrony, and so cannot help you reach your goal here.

To do what you want, you can use indirect recursion like so:

const go = (from = 10, to = 0, interval = 1000) => {
  setTimeout(() => {
    console.log(from--)
    if(from >= 0) {
      go(from)
    }
  }, interval)
}

go()

There is also a more modern approach that enables the use of syntax that looks a bit more familiar. This approach uses for await... of, the syntax for which does not appear to be supported by StackOverflow's transpiler:

const waitASec = () => new Promise((resolve) =>
  setTimeout(resolve, 1000))

async function* countdown() {
  for(let x = 10; x >= 0; x--) {
    await waitASec()  
    yield x
  }
}

for await(let y of countdown()) {
  console.log(y)
}

CodePudding user response:

The code below will countdown to zero.

var i = 10;
while (i > 0){
i--;
console.log(i);

}

  • Related