Jquery: Infinite loop and pause

10,722

Solution 1

One way is to put the code to be repeated in a function, and have the function repeat itself at the end:

var timeout = 1000;
var action = function() {
    // Do stuff here
    setTimeout(action, timeout);
};
action();

However, as ahren suggested, setInterval might be better:

var timeout = 1000;
var action = function() {
    // Do stuff here
};
setInterval(action, timeout);

The difference is slight, but if the machine is running slowly for some reason, the setInterval version will run the code every second on average, whereas the setTimeout version will run the code once each second at most.

Neither of those methods really work well with each(), however, so you'll need to store the sequence of popups somewhere and step through them:

var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
    var td = tds[index];
    var new_text = $(td).html();
    popup.html(new_text);
    popup.fadeIn('fast').delay(1000).fadeOut('slow');

    if(++index >= tds.length)
        index = 0;        
};
setInterval(action, timeout);
action();

Finally, to avoid moving to the next popup while the popup is hovered, you can add a check for that at the start of the function. It's also necessary to rearrange the animations so that they go "check for hover - fade out - change text - fade in".

var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
    if(popup.is(':hover'))
        return;

    var td = tds[index];
    var new_text = $(td).html();
    popup.fadeOut('slow', function() {
        popup.html(new_text);
    }).fadeIn('fast');

    if(++index >= tds.length)
        index = 0;        
};
setInterval(action, timeout);
action();

jsFiddle: http://jsfiddle.net/qWkYE/2/

Solution 2

If you like the short clean way, then use the jquery-timing plugin and write:

$.fn.waitNoHover = function(){
  return this.is(':hover') ? this.wait('mouseleave') : this;
};
$('#popups div').repeat().each($).fadeIn('fast',$)
  .wait(200).waitNoHover().fadeOut('slow',$).all()

See this on http://jsfiddle.net/creativecouple/fPQdU/3/

Share:
10,722
Neash
Author by

Neash

Updated on June 05, 2022

Comments

  • Neash
    Neash almost 2 years

    I have this code

    var timeout = 0;
     $('#container td').each(function(){
       var td = this;
       setTimeout(function() {
         var new_text = $(td).find(text).html();
         popup_text.html(new_text);
         popup.fadeIn('fast').delay(1000).fadeOut('slow');
       }, timeout);
       timeout += 1000 + 1000;
    });
    

    I get text from table cells and is displayed in the layer with a delay. 1 question: How do I make this code to run in an endless loop? 2 question: How to do that when you hover the mouse over popop cycle temporarily stopped and then continue? Thanks a lot!