Queuing setTimeout in javascript

I need to enable and disable an item. This works, but I don't really like the code. Is there a good way to do this?

setTimeout(function(){
  toggle();
  setTimeout(function(){
    toggle();
    setTimeout(function(){
      toggle();
      setTimeout(function(){
        toggle();
      }, 100);
    }, 100);
  }, 100);
}, 100);

I also use jQuery if this helps.

+3
source share
8 answers
function toggle_multiple(n)
{
    var toggled = 0;
    function toggle_one_time()
    {
        toggle();
        toggled += 1;
        if (toggled <= n)
            setTimeout(toggle_one_time, 100);
    }
    toggle_one_time();
}

And just call toggle_multiple(4).

+4
source

Recursive approach:

function multiTimeoutCall (callback, delay, times) {
    if (times > 0){
      setTimeout(function () {
        callback();
        multiTimeoutCall (callback, delay, times - 1);
      }, delay);
    }
}

Using:

multiTimeoutCall (toggle, 100, 4);

Edit: Another approach without populating the call stack:

function multiTimeoutCall (callback, delay, times) {
  setTimeout(function action() { // a named function expression
    callback();
    if (--times > 0) {
      setTimeout (action, delay); // start a new timer
    }
  }, delay);
}

I could use arguments.calleefunctions instead of the named expression, but it seems that it will become obsolete someday in ECMAScript 5 ...

+3
source

setInterval?

var toggler = function() {
    if (++self.counter >= self.BLINK_AMOUNT * 2) {
        self.counter = 0;
        window.clearInterval(self.timer);
        return;
    }
    toggle();
};
toggler.BLINK_AMOUNT = 1;
toggler.counter = 0;
toggler.timer = window.setInterval(toggler, 100);

, IE self - , .

+2

. jquery pulsate, , .

+1

:

for (var i= 0; i<4; i++)
    setTimeout(toggle, (i+1)*100);

, ,

+1

'unknown' setInterval,

function schedule(fn, max, delay)
{
    var counter = 0;
    var interval = setInterval(
        function()
        { 
            if(counter++ === max)
                clearInterval(interval);
            fn();
        }

       , delay);
}

:

schedule(toggle, 4, 100);
+1

, , jQuery? , . -

$("#message_box").fadeOut(450).fadeIn(350);

, -

$("#message_box").fadeOut(450).fadeIn(350).fadeOut(450).fadeIn(350);

0

:

function toggleMany(cnt) {
   toggle();
   if (--cnt >= 0) window.setTimeout('toggleMany('+cnt+')', 100);
}

toggleMany(4);
-2
source

Source: https://habr.com/ru/post/1718759/


All Articles