-3

I have written this javascript code to add images each after a delay of 3 seconds but this code is not working kindly help.

function start() {
    while(true) {
        setTimeout(addObstracles(), 3000)
    }
}

function addObstracle() {
        var element = document.createElement('img');    
        element.id = 'obs';
        element.className = 'obstracleAnimation';
        element.src = 'enemy.png';
        element.style.position = 'absolute';
        element.style.top = '0px';
        element.style.left = '100%';
        element.style.width = '150px';
        element.style.height = '100px';
        document.body.appendChild(element);
}
Sajal Ali
  • 419
  • 1
  • 6
  • 20

3 Answers3

3

setTimeout takes a function reference. You have a function invokation.

There are multiple ways to write this out:

setTimeout('addObstracles()', 3000) //i don't like this way
setTimeout(addObstracles, 3000) // pass the reference (I like this way!)
setTimeout(function() {
    addObstracles()
}, 3000) //I like this when `addObstracles has parameters!
Sterling Archer
  • 20,452
  • 15
  • 77
  • 107
2

Like Sterling mentioned in his anser, you are calling the function addObstracles instead of passing it to setTimeout, just i want to add to it that because you are setting timout functions on fixed intervals you can use setInterval function instead:

function start() {
    setInterval (addObstracles, 3000);
}

JSFiddle

razz
  • 8,452
  • 6
  • 45
  • 61
0

There are multiple issues with this code. I will add to the answers the following:

  • be careful what function you define and what function you call: something != somethings

  • be careful where you call your start() function: it has to be after the body tag or body.appendChild won't exist

  • be careful how you style your element. With the current styling, it is not displayed at all. I have just removed element.style.position = 'absolute'; to make it visible

  • make sure the image you are trying to display is in the same folder as the script

NovaLogic
  • 630
  • 13
  • 20