Combine for loop with timing events in javascript -
I have this code:
for (i = 0; i & lt ; 3; I ++) {var interval = set interval (function () {warning (i);}, 2000); }
What I would like to achieve is that every 2 seconds displays 0 times, then 1 and finally 2.
Instead of waiting me enough Is there a 3 alert to display number 3, before my code is wrong?
OK, this problem has more than one solution (again) but, first Why Your code does not work properly.
Your code:
for (I = 0; i
.. Basically it means that it will be done by three seconds after two seconds for fasting as fast as the three setInterval
calls Will give in the form. So basically, all your calls actually run fast after 2 seconds, only a few milliseconds or less between them. In addition, setInterval
means that unless the clearInterval
is called with the variable, it will be called. In other words, your code does not execute the alert, because you are never calling clearInterval
. In the end, your alert (i)
will always display the value of 3, Because this is the last value of i
when the execution goes away from to
for loop.
To improve your code, you can completely remove the loop and as long as the value of i
is notified to all, SetInterval
Give Times; At that point, you can only call clear intervals
at the price that deals with setInterval
and the job is over.
Working code:
// value to start output var i = 0, // start setInterval and the variable interval of your handle Assign to, // it is used to clear the gap when the execution interval should end = SetInterval (function () = // the alert value and 1 alert (i ++); // if I'm equal to 3 and does not call more (i === 3) {// Clear the interval method will not be called clear in the future Interval (interval);}}, 2000); Cheers, hopefully you've learned something new today.
Comments
Post a Comment