0

I'm trying to have a 2 second delay in between when some p tags get added to the dom. This is what I've got so far.

var inputs = ['blah','blah blah', 'blah blah blah'];

function insertInput(input){
  inputs.forEach(function(input){
    var commandP = document.createElement('p'),
    textNode = document.createTextNode(input),
    newInput = document.getElementById('first_input');
    commandP.appendChild(textNode);
    commandP.className = 'inputs';

    delayInsert(newInput, commandP);
  })
}

function delayInsert(input, command){
    setTimeout(function(){
      input.appendChild(command);
    }, 2000)
}

insertInput(inputs);

Don't usually use setTimeout often so the answer isn't readily apparent to me but all the dom nodes get added at the same time. If anyone has a solution as to how to go about spacing the insertion of the nodes apart, and to explain why this behavior is occurring in the first place as I'm pretty curious now, I'd greatly appreciate it.

1 Answers1

2

Your forEach calls execute at the same time (give or take) so you get multiple calls to setTimeout at the same time with the same delay, so the functions all execute at the same time.

To tweak that, you just need to modify the delay given to the setTimeout

function insertInput(input) {
    inputs.forEach(function (input, i) {
        // ...
        delayInsert(newInput, commandP, (i + 1) * 2000);
    })
}

function delayInsert(input, command, delay) {
    setTimeout(function () {
        input.appendChild(command);
    }, delay);
}
James Long
  • 4,629
  • 1
  • 20
  • 30