4

I'm trying to execute two different functions at the exact same time.

I have a row of images, and one after the other they light up by changing their opacity, to make it look like they're blinking. Problem is that the timing needs to be exact, and with the few milliseconds of difference, after a minute or two it just looks like a mess.

    <img src="img1" class="1" /><img src="img2" class="2" /><img src="img3" class="3" />

    <script type="javascript">
    setTimeout(function blinkone(){$('.1').delay(1000).fadeTo(0,0.5).delay(2000).fadeTo(0,1, blinkone);},1000)

    setTimeout(function blinktwo() {$('.2').delay(1000).fadeTo(0,0.5).delay(2000).fadeTo(0,1, blinktwo);},2000)

    setTimeout(function blinkthree() {$('.3').delay(1000).fadeTo(0,0.5).delay(2000).fadeTo(0,1, blinkthree);},3000)
    </script>

How can I execute multiple functions at the exact same time?

Sera
  • 43
  • 1
  • 3

3 Answers3

4

Javascript is single-threaded, so you cannot execute many functions at the EXACT same time, literally. You could work around this by grouping your setTimeout call, eg:

var iterationCount = 0;
setTimeout(function(){
   iterationCount++;
   $('.1').delay(1000).fadeTo(0,0.5).delay(2000).fadeTo(0,1, blinkone);
   if (iterationCount % 2 == 0) {
      $('.2').delay(1000).fadeTo(0,0.5).delay(2000).fadeTo(0,1, blinktwo);
   }
   if (iterationCount % 3 == 0) {
      $('.3').delay(1000).fadeTo(0,0.5).delay(2000).fadeTo(0,1, blinkthree);
   }
},1000);

This way, you avoid losing the sinchronization between animations.

LittleSweetSeas
  • 6,786
  • 2
  • 21
  • 26
2

Just give them all the same class and affect that class. http://jsfiddle.net/popnoodles/amD8T/2/

<img src="img1" class="blink" />
<img src="img2" class="blink" />
<img src="img3" class="blink" />

<script>
$(function(){

    offon();

});

function offon()
{
    $('.blink').animate({opacity:0},1000)
        .animate({opacity:1},1000, function(){
            offon();
        });
}
</script>
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
0

You could also chain the callbacks recursively, which is a lot cleaner IMO:

function display(number){
    number = number || 1
    $('.'+ (number % 3 + 1)).delay(1000).fadeTo(0,0.5).delay(2000).fadeTo(0,1, function(){display(++number);});
}

This also scales well, so you don't have to add 100 lines of code to add the effect to 100 images.

Here is a demonstration: http://jsfiddle.net/8cwA6/1/

I'm not entirely sure, but maybe the effect you want is more like this fiddle: http://jsfiddle.net/8cwA6/2/

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • Thank you so much! This worked perfectly, it was exactly what I needed! (And since this will probably have 20-30 images, the easy scalability of it is awesome.) – Sera Nov 26 '12 at 02:40