1

I am still a newbie at Javascript. I tried writing a program to make images fadeToggle all the time, so I used the while conditional statement (combined with a constant variable); after running that and freezing my computer (then remembering that viruses are basically infinite operations) I searched on here a bit, realized I should probably, indeed, never use infinite loops.

(Actually I want shimmer -- meaning to go from opacity 0.9 to 0.6 to 0.9 etc...) so its not the same as fadeToggle, but the same question remains; how do I make it go infinitely?(without writing malicious code.)

This is what I wrote, for your reference:

<script>
$(document).ready(function(){
var always10 = 10;
while (always10 == 10) {
    $('.pimg').fadeToggle(2600);
                   }
});
</script>

Also, I've found out on another thread that while(true) is better for infinite loops. So another question: are infinite loops sometimes OK?

Le Jeune
  • 13
  • 3
  • 2
    Inifinite loops are almost never OK in Javascript. It's single-threaded, so you'll never be able to interact with the document. Use `setInterval()` to run a function periodically in the background. – Barmar Oct 25 '13 at 20:04

2 Answers2

0

Just use callbacks already provided by jQuery animations like .fadeToggle:

function fadeToggleForever ($e) {
    $e.fadeToggle({
        duration: 2600,
        // start another fadeToggle when this one completes
        complete: function () { fadeToggleForever($e) }
    });
}

// main code
fadeToggleForever($('.pimg'));

The of using the complete callback works because jQuery animations internally use setTimeout (or perhaps setInterval) and thus "yield" code execution so that the browser can continue reacting to user input and updating the display.

user2864740
  • 60,010
  • 15
  • 145
  • 220
0

Since Javascript is asynchornous there is no sleep methode. But instead, a good idea is to use setInterval or setTimeout.

Without these function, your loop is going to take as most ressources as it can and it can result in a freeze (depending on your browser).

Binary Brain
  • 1,170
  • 8
  • 20
  • Asynchornous and sleep mode = goes over my head (I do not speak another programming language so :-P), but the setInterval and setTimeout solves my question. Like another poster, I wanted to write my own, so I didn't go with jquery. Thanks to all! – Le Jeune Oct 25 '13 at 21:12