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
forloop in my async function foofunction sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }I tried
setTimeoutbut I wasn't able to achieve any valid result.If I wrap in
setTimeoutthis piece of code:('$someDiv').css({'background-color': 'red'});then after specified amount of time all$someDiv'schange css style together (keep in mind that$someDivrefers to different DOM element with eachwhileloop iteration).If I wrap in
setTimeouta piece of code withif,elsestatements 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?