Question

I have the following for loop:

for (var i = tileLog.length - 1; i >= 0; i--) {
    $('.' + tileLog[i]).mouseenter();
};

1 < tileLog.legth < 1025

Is there a way to delay each iteration of the loop so that mouseenter() is triggered every x miliseconds?

I have tried:

function doSetTimeout(i) {
    setTimeout(function() { $('.' + i).mouseenter(); }, 250);
}

for (var i = tileLog.length - 1; i >= 0; i--)
  doSetTimeout(tileLog[i]);

This doesn't seem to work, it just delays by 250ms then iterates through the loop

Was it helpful?

Solution

As an alternative to using setTimeout() you could also use setInterval().

Define a running variable in the outer scope (like your running i in the loop). In each iteration, besides calling your function, decrement the running variable. If it is below zero, stop the setInterval()`` :

var index = tileLog.length - 1,
timer = setInterval( function(){

  $('.' + tileLog[index]).mouseenter();

  index -= 1;
  if ( index < 0 ) {
    clearInterval( timer );
  }
}, 250 );

There is no actual sleep() function or something similar. Would also be problematic as JavaScript (for most cases) is single threaded and such a method would block the render thread, thus rendering your browser inaccessible.

OTHER TIPS

There is no sleep or such in JavaScript. So your approach with timeout is correct.

var tileLog;
var i = titleLog.length - 1;

function func1() {
   $('.' + tileLog[i]).mouseenter();
   if (--i) {
     window.setTimeout(func1, 250);
   }
}

// and of course start the process
func1();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top