123456 should be displayed in the alert, but unfortunately, undefined is displayed :(

<script type="text/javascript"> function _query(id) { setInterval(function() { $.get('/query.php', function(data) { if(data == 1) alert(id); // undefined }); }, 10000); } _query(123456); </script> 
  • Are you sure that the code is exactly the same as where you have undefined ? This code is fully working. - lampa
  • one
    that is why it is better to avoid using it: setTimeout (function loop () {console.log ('looping'); setTimeout (loop, 500);}, 500) - Specter
  • 2
    more than known: var counter = 0, timer = setTimeout (function loop () {if (++ counter> 5) {// 5 iterations clearTimeout (timer)} else {console.log ('looping'); timer = setTimeout (loop, 500);}}, 500) - Specter
  • 2
    @Spectre, if (++ counter> 5) {// 5 iterations, and what is this for? - Moda
  • one
    and unless without clearTimeout it will not be completed? Read already about the docks, enough guessing. - KaZaca

1 answer 1

 <script type="text/javascript"> function _query(id) { setInterval(function(id) { $.get('/query.php', function(data) { if(data == 1) alert(id); // undefined }); }, 10000, id); } _query(123456); </script> 

To pass an argument to a function called via setInterval, pass this argument to setInterval itself after 2 arguments - execution delay.

The code above has worked for me personally.

  • it will work without passing id to the called function. - lampa