Good day.
It is necessary to make an infinite change of pictures. My suggestion:

while(1) { $('#1').toggle(); $('#2').toggle(); } 

Confused while (1): all my life they said not to do, but here. Is this solution correct? Are there any alternative ways to implement? (Do not offer a for loop :))

  • five
    Most likely, you need setInterval - Dmitry
  • 2
    Try setInterval - therainycat
  • one
    what to measure correctness? This solution works in principle - Grundy
  • one
    @Grundy just the rest stops working :) - Pavel Mayorov
  • one
    @PavelMayorov, but the rest was out of the question: P - Grundy

2 answers 2

everything else stops working because you are in synchronous (read, single-threaded) mode starts a loop in which the script gets stuck - since while(true) - is always executed, because the condition true always true.

Moreover, since it runs without time limits (no sleep, relatively speaking), it eats CPU resources non-metrically, all other scripts, even asynchronous, may well begin to slow down.

as @Dmitry correctly said, use setInterval

 setInterval(function(){ alert("Hello"); }, 3000); 

the link example will work in asynchronous mode, causing the function to execute at intervals of 3 seconds

    requestAnimationFrame() as an alternative to setInterval() :

     var img = document.getElementById('e-img') ,src = [ 'https://www.gravatar.com/avatar/cbfaff96665b7567defe1b34a883db8b?s=32&d=identicon&r=PG' ,'https://graph.facebook.com/10204328181386038/picture?type=large' ] ,start ,current = 0 ; function step(timestamp) { var progress; if( !start) start = timestamp; progress = Math.round((timestamp - start) / 500) % 2; if( current != progress) { current = progress; img.src = src[current]; } requestAnimationFrame(step); } requestAnimationFrame(step); 
     <img src="" alt="" id="e-img" width="32" height="32" border="0"> 

    In everyday language, the function is called every time the browser is ready to redraw the screen. If it does not load anything, it is often. If pondered, then less. In this task, super frequent rendering is not needed, and the requestAnimationFrame() application here has only one advantage: more accurate timing than setInterval() .

    F-I step() is called as often as the browser is ready to draw something. We remember the start time, and make sure that at least 1/2 second passes, and then we change the picture.