-1

Problem

My for loop in JS is just passing all of the elements without waiting for timeout, I tried few things like checking setTimeout in for-loop does not print consecutive values this topic but couldn't find any solution.

What I Want

I want my for loop to wait for timeout for every element in array.

Code

function generateList(level) {
    //her levelda olusacak parca sayisi 1 artar
    generatedList = [];
    for (var x = 0; x < level; x++) {
        //her blok arasına timeout koymak istiyorum
        generateNext();
        setTimeout(function() {}, 400);
        //timeout doesn't work between elements
    }
}

function generateNext() {
    // bu kısım sonraki seviye için tek bir parça hazırlar
    var random = Math.floor(Math.random() * 4) + 1;
    var name = constList[random - 1];
    $("#" + name).fadeIn(100).fadeOut(100).fadeIn(100);
    playSound(name);
    generatedList.push(random);
}

I want to call generateNext() function after 400 ms but here, my code calls all of them at the same time

Emir Kutlugün
  • 63
  • 3
  • 17

2 Answers2

1

Answer for the problem is that, setTimeout is asynchronous, it cannot delay the synchronous execution until unless either pushed to stay synchronous .

For this usage you want to use setInterval instead of setTimeout

function generateList(level) {
    //her levelda olusacak parca sayisi 1 artar
    generatedList = [];
    let counter = 0
    const interval = setInterval(generateNext, 400)
}



function generateNext() {
    // bu kısım sonraki seviye için tek bir parça hazırlar
    if (counter === level) {
      clearInterval(interval)
    }
    var random = Math.floor(Math.random() * 4) + 1;
    var name = constList[random - 1];
    $("#" + name).fadeIn(100).fadeOut(100).fadeIn(100);
    playSound(name);
    generatedList.push(random);
    counter++
}
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
0

Put generateNext() inside the timeout function

setTimeout(function() {
   generateNext()
}, 400);
Mahmoud Y3c
  • 94
  • 1
  • 9