+ 1

Having problems with setTimeout

Hey there, I have a simple function that won't work for some reason. The code is: for (i=0; i<100; i++) { setTimeout(function() { element.style.height = i+"px"; }, 10); } As you can see, all I want to do is create a simple animation that will take 1 second (100 iteration × 10 ms per each). The problem is that the enimation doesn't work, and instead I get the final result after 10 ms (I've changed it to 1000ms the the final result just "poped" without any animation after 1 second). Any ideas what's wrong here?

12th Nov 2018, 3:57 AM
Yoni Simian
7 ответов
+ 3
setInterval should work for you. If you need to stop it after some iterations, then you need to store setInterval in a variable like var myInterval= setInterval(function (){}, interval) And parallely you'll need to increment i and check if i crosses a defined value then call clearInterval(myInterval)
12th Nov 2018, 5:55 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 2
Instead, try using setInterval() and without that for loop. It should solve your problem.
12th Nov 2018, 4:33 AM
Шащи Ранжан
Шащи Ранжан - avatar
+ 1
I have timer example, idk if this one is the best or not Look at the js line83, sleep function https://code.sololearn.com/W2UIc7eCOx54/?ref=app
12th Nov 2018, 4:33 AM
Taste
Taste - avatar
0
SetTimeout run asynchronosly in their own thread They probably initiated at same time, and run at same time
12th Nov 2018, 4:19 AM
Taste
Taste - avatar
0
So is there any way to fix it? Or any other way to make this animation?
12th Nov 2018, 4:30 AM
Yoni Simian
0
The setInterval didn't help me much because I still needed an i variable to stop the function from going on forever, and I didn't make it very well. The "sorter with display" helped me a lot, I didn't even know what an async function is, so thanks, but it's still not very smooth (it seems that the same loop can end in about 500-1500ms, depends on how much is my phone busy at the moment...)
12th Nov 2018, 5:31 AM
Yoni Simian
0
For more consistent display, you can use delta time.
12th Nov 2018, 5:40 AM
Taste
Taste - avatar