Llamar a una función cada 60 segundos


Usando setTimeout() es posible lanzar una función en un momento especificado:

setTimeout(function, 60000);

Pero ¿qué pasa si me gustaría lanzar la función varias veces? Cada vez que pasa un intervalo de tiempo, me gustaría ejecutar la función (cada 60 segundos, digamos).

Author: Samuel Liew, 2010-06-29

8 answers

Si no le importa si el código dentro del timer puede tomar más tiempo que su intervalo, use setInterval():

setInterval(function, delay)

Que dispara la función pasada como primer parámetro una y otra vez.

Un mejor enfoque es, usar setTimeout junto con una función self-executing anonymous:

(function(){
    // do some stuff
    setTimeout(arguments.callee, 60000);
})();

Que garantiza, que la siguiente llamada no se realiza antes de que su código fue ejecutado. Usé arguments.callee en este ejemplo como referencia de función. Es una mejor manera de darle un nombre a la función y llamarla dentro de setTimeout porque arguments.callee está obsoleto en ecmascript 5.

 311
Author: jAndy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-29 07:47:54

Utilice el

setInterval(function, 60000);

EDITAR: (En caso de que desee detener el reloj después de que se inicia)

Sección del script

<script>
var int=self.setInterval(function, 60000);
</script>

Y Código HTML

<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>
 54
Author: BlueBird,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-01 12:27:20

Un mejor uso de jAndy's respuesta para implementar una función de sondeo que sondea cada interval segundos, y termina después de timeout segundos.

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000;

    (function p() {
        fn();
        if (((new Date).getTime() - startTime ) <= timeout)  {
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

UPDATE

Según el comentario, actualizándolo para la capacidad de la función pasada para detener el sondeo:

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000,
    canPoll = true;

    (function p() {
        canPoll = ((new Date).getTime() - startTime ) <= timeout;
        if (!fn() && canPoll)  { // ensures the function exucutes
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

function sendHeartBeat(params) {
    ...
    ...
    if (receivedData) {
        // no need to execute further
        return true; // or false, change the IIFE inside condition accordingly.
    }
}
 19
Author: Om Shankar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:32

En jQuery puedes hacer esto.

function random_no(){
     var ran=Math.random();
     jQuery('#random_no_container').html(ran);
}
           
window.setInterval(function(){
       /// call your function here
      random_no();
}, 6000);  // Change Interval here to test. For eg: 5000 for 5 sec
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="random_no_container">
      Hello. Here you can see random numbers after every 6 sec
</div>
 10
Author: Optimum Creative,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-09 17:27:03
setInterval(fn,time)

Es el método que buscas.

 7
Author: Jamiec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-29 07:45:10
 6
Author: christian louboutin sale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-22 06:15:52

Simplemente puede llamar a setTimeout al final de la función. Esto lo añadirá de nuevo a la cola de eventos. Puede utilizar cualquier tipo de lógica para variar los valores de retardo. Por ejemplo,

function multiStep() {
  // do some work here
  blah_blah_whatever();
  var newtime = 60000;
  if (!requestStop) {
    setTimeout(multiStep, newtime);
  }
}
 6
Author: John Henckel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-30 15:23:39

Hay 2 maneras de llamar-

  1. setInterval(function (){ functionName();}, 60000);

  2. setInterval(functionName, 60000);

La función anterior llamará cada 60 segundos.

 0
Author: Gaurav Tripathi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-07 10:47:35