2010-06-15 16 views

risposta

34
var counter = 0; 
setInterval(function() { 
    ++counter; 
}, 1000); 

Inoltre, se mai hai bisogno di spegnerlo di nuovo, questo lo rende possibile:

var counter = 0; 
var myInterval = setInterval(function() { 
    ++counter; 
}, 1000); 

// to stop the counter 
clearInterval(myInterval); 
+0

@ShintoJoseph - Vuoi dire che non credi che si aggiunge al DOM? Non era questa la domanda, e questa risposta è stata accettata per quasi cinque anni. –

+0

sì ha funzionato grazie –

0

Il modo più semplice è setInterval("x++",1000);, dove x++ può essere sostituito con il vostro incremento. Esempio:

JavaScript/jQuery

var x=0; 

setInterval("x++",1000); // Increment value every second 

// Let's just add a function so that you can get the value 
$(document).ready(function() { 
    $("#showval").click(function(){ 
    alert(x); 
    }); 
}); 

HTML

<a href="#" id="showval">Show value</a> 
+0

'setInterval (" x ++ ", 1000);' utilizza un'eval implicita(). Nella maggior parte dei casi non è un problema, ma non è tecnicamente un rischio per la sicurezza? –

+0

Se lo era, perché non l'hanno disabilitato? È ancora il modo più semplice per aumentare una variabile. –

0

un modo migliore è tramite la funzione di chiusura:

function setIntervalTimes(i_func, i_sleep, i_timesRun){ 
     var timesRun = 0; 
     var interval = setInterval(function(){ 
      timesRun += 1; 
      if(timesRun === i_timesRun){ 
       clearInterval(interval); 
      } 
      i_func(); 
     }, i_sleep); 
    }, 
+0

Puoi spiegare perché è meglio della risposta accettata? – AXL

0

funzione timer (seco nds, elemento)
autore: Zmora JLB
email: zmorajlb [scimmia] gmail.com

Includere imballato Funzione Timer:

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+ ((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)) {while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'}; c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('2 p=\'- s tńu -\';h m(c){2 g=d.f(c/r);2 i=d.f((c/e)%e);2 8=c%e;2 4=\'\';7(g>0){4=4+\'\'+g+\' w \'}7(i>0){4=4+\'\'+i+\' q \'}7(8>0){4=4+\'\'+8+\' v\'}y 4}h D(8,j,E){2 l=b a();2 5=b a();2 o=b a();2 9=b a();9=8;l=(x*d.f(d.B()*6)+1)*3;5=0;o=A(h(){k=9-5;7(5<9){5++}7(5==9){$(\'#\'+j).n(p)}z{$(\'# \'+j).n(m(k))}},C)}',41,41,'||var||out|counter||if|seconds|destination|Array|new|val|Math|60|floor|hours|function|minutes|element|remaining|number|secondsToText|html|interval|end_text|minut|3600|budowa|zako|czona|sekund|godzin|33|return|else|setInterval|random|1000|timer|method'.split('|'),0,{})) 

uso

.248.913.032,62321 milioni

secondo: Conteggio "3605" secondi -: -