0

Can we call 2 setInterval() function one after another

var f = setInterval(moveForward , 1); var b = setInterval (moveBackward, 1);

5th Aug 2017, 12:44 PM
Chinmay Mishra
Chinmay Mishra - avatar
1 Odpowiedź
+ 4
You can call/register any number of time interval you want... but due to specificity of this running way, that's not the good way to chain functions execution... By writting: var f = setInterval(moveForward , 1); var b = setInterval (moveBackward, 1); you call the second one immediatly after calling the first (not waiting for execution of callback function). Anyway, as there's no real multi-task when running a JS script, giving them same delay will produce the expected result, but you'll have not the expected result if you delay them differently: var f = setInterval(moveForward , 5000); var b = setInterval (moveBackward, 1); ... in such case, moveForward() will be executed after 5s, but moveBackward() will run immediatly ^^ To chain execution, you'll have to rather use setTimeout(), or handling your setInterval reference inside the callback to clear the timer, before recall another (but setTimeout is very better suited for that): function moveForward() { /* code to execute */ setInterval(moveBackward,1); } function moveBackward() { /* code to execute */ setInterval(moveForward,1); } moveForward(); // a simple call is enough to run the "intervaled-loop" ;) But don't care if order of execution of those functions isn't important ^^
5th Aug 2017, 1:00 PM
visph
visph - avatar