Project FH Project FH - 5 months ago 28
jQuery Question

setTimeout with changing timeout value

I'm working on some timeout in jQuery but I got a problem with my timeout value.
So, I got an array of value (Ex : ["2490", "4200"]), and I want my timeout to print the value of the array after 2490ms, then go back to 0 and finaly print the next value of the array after 4200ms. But it never go back to 0

Actualy, this is the jQuery code :

var array = ['2490', '4200'];
var mytimeout;

for (var i = 0; i < array.length; ++i)
{
doTimeout(i);
clearTimeout(mytimeout);
}

function doTimeout(i) {
mytimeout = setTimeout(function() {
$('#text').append(array[i]);
}, array[i]);
}


JSFIDDLE : https://jsfiddle.net/2aftscou/

So everything seems to work except the fact that I want my timer to be reinitialize at 0 when it ends (that's why I've used clearTimeout(), but it doesn't work in this case).

I really don't know what to do

Answer

Your current implementation is clearing the timeout right away. You can chain the timeouts together with something like this

var array = ['2490', '4200'];
var mytimeout;

function doTimeout(i) {
  mytimeout = setTimeout(function() {
    $('#text').append(array[i]);
    if (i <= array.length)
      doTimeout(i + 1);
  }, array[i]);
}

doTimeout(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="text">

</p>