Let for loop wait until code finish execution javascript -


i have bubble sort function when swap occurs should show visibly. after lots of approaches continues executing loops without waiting animation stop. (we allowed use javascript). there way tell website wait animation complete. here snippet of code:

for (var = 0; < len; i++)  {      (var j = 0, swapping, endindex = len - i; j < endindex; j++)      {         if (marksarr[j] > marksarr[j + 1])          {             //swap objects                 /*(function() {                 var k = 0,                     action = function() {                         document.getelementbyid(courseskey[j]).style.top = (parseint(document.getelementbyid(courseskey[j]).style.top) + 1) + 'px';                         document.getelementbyid(courseskey[j + 1]).style.top = (parseint(document.getelementbyid(courseskey[j+1]).style.top) - 1) + 'px';                           k++;                         if (k < difmoves) {                             settimeout(action, 200);                         }                     };                  settimeout(action, 200);             })();*/            }     } } 

as @cookie monster explained, can't block loops in javascript , update ui using settimeout() @ same time (this because javascript single-threaded).

the elegant solution "recording" each animation step while for loops process array, , run animation afterwards, e.g. using settimeout(). time ago, i've implemented approach similar question on stackoverflow; here's demo: jsfiddle

the code can simplified:

function swap(list, i1, i2) {     var tmp = list[i1];     list[i1] = list[i2];     list[i2] = tmp; }  function animatebubblesort(list) {     var animationsteps = [];      // sort array     (var n = list.length; n > 1; --n) {         (var = 0; < n-1; ++i) {             if (list[i] > list[i+1]) {                 swap(list, i, i+1);                 // add new step (clone of current array) "animation queue"                 animationsteps.push(list.slice(0));             }         }     }      // print animated steps (using setinterval() simplicity)     var count = 0,          interval = setinterval(function(){             console.log(animationsteps[count]);             if (++count >= animationsteps.length) {                 clearinterval(interval);             }         }, 250); }  animatebubblesort([5,8,2,4,1,9,7,3,0,6]); 

demo

another (less intuitive) possibility implement algorithm without loops in order control on when next step of algorithm executed (so have time animation). here's example: demo 2


Comments

Popular posts from this blog

c# - Unity IoC Lifetime per HttpRequest for UserStore -

Change the color of an oval at click in Java AWT -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -