I have a function foo
and I wanted to add a sleep/wait function to make a kind of DOM elements animation. I've already done some research and I know that it's impossible to pause a javascript function because it freezes browser - correct me if I'm wrong. How can I overcome it?
function foo() {
while (someCondition) {
var $someDiv = $('.someDiv:nth-child(' + guess + ')');
$someDiv.css({'background-color': 'red'});
wait 1000ms
$someDiv.css({'background-color': 'blue'});
wait 1000ms
if (someCondition2) {
doSomething; }
else {
for loop }
}
}
$someDiv
refers to different DOM element with each while
loop iteration because variable guess
changes
What I've tried
I used the function below and it worked but the problem is I couldn't use a
for
loop in my async function foofunction sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
I tried
setTimeout
but I wasn't able to achieve any valid result.If I wrap in
setTimeout
this piece of code:('$someDiv').css({'background-color': 'red'});
then after specified amount of time all$someDiv's
change css style together (keep in mind that$someDiv
refers to different DOM element with eachwhile
loop iteration).If I wrap in
setTimeout
a piece of code withif
,else
statements then I've got an error - Infinite Loop
Question
The foo function is simplified just for visualisation the problem. The original function I'm working on you can find on codepen (findNumber
function)
I want to make a binary search algorithm animation. Something similar to this
How can I achieve the desired result?
In general: How can I animate DOM elements in a loop with interval between each iteration?