0

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

6
  • As timer is cleared, callback will not be called.. Commented Jun 23, 2016 at 19:58
  • Is this the desired behavior? jsfiddle.net/Lbjfafpz Commented Jun 23, 2016 at 20:00
  • Yes it is, thanks dude. Commented Jun 23, 2016 at 20:02
  • Note: I think setTimeout() only executes once in any case, clearTimeout() is only needed if you want to cancel the one timeout before it happens. setInterval() is repeating. Commented Jun 23, 2016 at 20:04
  • @ebyrob You're right, thanks for the correction Commented Jun 23, 2016 at 20:05

2 Answers 2

1

This will not work. Your timeout will be killed after start. You have to start new timeout after old timeout will be executed.

Something like this

function doTimeout(i) {
    mytimeout = setTimeout(function() {

    $('#text').append(array[i]);
    i++;
if (i<array.length) {
doTimeout(i)
 }

   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>

1 Comment

That worked, thanks man I'm not used to Javascript to be honnest ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.