So che questo è un necroposting ma penso ancora persone sono alla ricerca di questo.
Questo è quello che uso: 3 variabili:
t
per millisecondi dal ..Data Oggetto per prossimo obiettivo
timerSys
per l'intervallo effettivo
seconds
soglia per millisecondi è stata fissata
prossimo ho un function timer
con 1 variabile la funzione verifica se la variabile è veramente, in caso affermativo si controlla se il timer è già in esecuzione e se questo è il caso che riempie le vars globali, se non veramente, falsamente, cancella l'intervallo e impostareDaa false;
var t, timerSys, seconds;
function timer(s) {
if (s && typeof s === "number") {
if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
timerSys = setInterval(function() {
sys();
}, s);
t = new Date().setMilliseconds(s);
seconds = s;
}
} else {
clearInterval(timerSys);
timerSys = false;
}
return ((!timerSys) ? "0" : t)
}
function sys() {
t = new Date().setMilliseconds(seconds);
}
esempio I
ora è possibile aggiungere una riga al funzione SYS:
function sys() {
t = new Date().setMilliseconds(seconds);
console.log("Next execution: " + new Date(t));
//this is also the place where you put functions & code needed to happen when interval is triggerd
}
ed eseguire:
timer(5000);
Ogni 5 secondi in console:
//output:: Next execution: Sun May 08 2016 11:01:05 GMT+0200 (Romance (zomertijd))
Esempio II
function sys() {
t = new Date().setMilliseconds(seconds);
console.log("Next execution: " + seconds/1000 + " seconds");
}
$(function() {
timer(5000);
});
Ogni 5 secondi in console:
//output:: Next execution: 5 seconds
Esempio III
var t, timerSys, seconds;
function timer(s) {
if (s && typeof s === "number") {
if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
timerSys = setInterval(function() {
sys();
}, s);
t = new Date().setMilliseconds(s);
seconds = s;
}
} else {
clearInterval(timerSys);
timerSys = false;
}
return ((!timerSys) ? "0" : t)
}
function sys() {
t = new Date().setMilliseconds(seconds);
console.log("Next execution: " + seconds/1000 + " seconds");
}
$(function() {
timer(5000);
$("button").on("click", function() {
$("span").text(t - new Date());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Freebeer</button>
<span></span>
Nota questo modo si può andare al di sotto di 0
fonte
2016-05-08 09:20:46
-1 patrick, questo non è un principio mondano. a volte hanno risorse utili. – JoeRocc
OT: il problema è distinguere quelle volte dagli altri :) Senza conoscere l'argomento, ovviamente – superjos
"Normalmente annullo la variabile timer nel timeout" –