Search code examples
javascriptsettimeoutdelaysetinterval

How to go through a queue with a loop, which includes a delay? (JavaScript)


I want to add some elements (in this case the numbers) to the queue and if a condition is true (in this case "invert"), then I want the numbers to be inverted and then added to the queue. After it I want the start() function to print the numbers in the console with a delay of 1 second. For example the numbers of the sample code should be printed like after 1 sec: "1", after 2 sec: "-2", after 3 sec: "-3" and when the time is equal to the queue.length then the last number should be printed, so in this case it would be the "4" after 4 seconds. Could anyone please give me a function, which can solve this problem? thanks.

var queue = [];
var invert = false;

queue.push("1");
invert = true;
queue.push("2");
queue.push("3");
invert = false;
queue.push(4);

// queue should look like this
// queue = [ '1', '-2', '-3', '4' ]

var queueLenght = queue.length;
function start() {
        for(var i = 0; i < queueLenght; i++){
            console.log(queue.shift());
        }
}

start();


Solution

  • Is this what you're looking for?

    //generate queue
    var queue = [];
    var invert = false;
    
    function addNumber(n){
      queue.push(invert?-n:n);
    }
    
    addNumber('1');
    invert = true;
    addNumber('2');
    addNumber('3');
    invert = false;
    addNumber('4');
    
    //set interval
    var interval=setInterval(function(){
      if(queue.length){
        console.log(queue.shift());
      }
      else{
        clearInterval(interval);
      }
    },1000)

    This generates the queue properly, creates an interval which executes code every 1000ms, then clears it once it finishes.