Foro de elhacker.net

Programación => Desarrollo Web => Mensaje iniciado por: WHK en 6 Diciembre 2011, 14:02 pm



Título: Alternativa al setinterval o sleep en javascript
Publicado por: WHK en 6 Diciembre 2011, 14:02 pm
A veces necesitamos hacer un sleep sin utilizar setinterval o settimeout, me ha pasado a mi por diferentes motivos y se me ocurrió hacer un pequeño script que utiliza animaciones para retardar la ejecución del resto del código, se que no es algo nuevo pero talves le pueda servir a algunos

Código
  1. <head>
  2. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  3. </head>
  4. <body>
  5. $(document).ready(function(){
  6. function check(){
  7. /* Mi código acá */
  8.  
  9. /* sleep */
  10. $('#sleep').fadeOut('slow', function(){
  11. $('#sleep').fadeIn('slow', check());
  12. });
  13. }
  14. check();
  15. });
  16. </script>
  17. Verificando <span id="sleep">_</span>
  18. </body>
  19. </html>

Un reloj con esto:
Código
  1. <head>
  2. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  3. </head>
  4. <body>
  5. $(document).ready(function(){
  6. function check(){
  7. var h = new Date();
  8. $('#reloj').text(h.getHours() + ':' + h.getMinutes() + ':' + h.getSeconds());
  9. /* sleep */
  10. $('#sleep').fadeOut(1000, function(){ /* 1 segundo de intervlo */
  11. $('#sleep').fadeIn(0, check());
  12. });
  13. }
  14. check();
  15. });
  16. </script>
  17. Reloj: <span id="reloj"></span> <span id="sleep"></span>
  18. </body>
  19. </html>

Saludos.