0

I'm not able to pass an index from an array to the 2nd argument of a window.setTimout() function (https://www.w3schools.com/js/js_timing.asp)

function joueursCascade(){

     for (i = 0; i <= my_params.nbJoueurs; i++) {
        var del = tabDel[i]; c

        function getName(){

        message = new Paho.MQTT.Message(document.getElementById('btn3').value);


        message.destinationName = document.getElementById('esp'+i).value+"/ledstate";

        mon_client.send(message);

        }       
    window.setTimeout(getName(), del);
    }
}

called by something like joueursCascade() this code should send "my_params.nbJoueurs" strings via MQTT at "del" time intervals.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
lairom
  • 1
  • 2
  • I'm not sure I understand what you're trying to do here. The second argument to the setTimeout is the duration for the timeout. – Taplar May 29 '19 at 17:54
  • Also `getName()` is going to execute immediately due to the `()` – Taplar May 29 '19 at 17:55
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Taplar May 29 '19 at 17:57
  • See also [Calling functions with setTimeout()](https://stackoverflow.com/q/3800512/215552) – Heretic Monkey May 29 '19 at 19:07

2 Answers2

0

Yes, you just need to make sure that your del variable is numerical.

Try to add parseInt(del)

Otherwise that question was already answered here

Ange Loron
  • 1,093
  • 1
  • 11
  • 23
0

window.setTimeout(getName(), del);

Should be:

window.setTimeout(getName, del);

If you pass getName() as 1st argument, then you are in fact passing the return value of that function. You need to pass in a reference to that function, hence only getName

JME
  • 483
  • 2
  • 5