Script Cronometru

Discutii si intrebari legate de scripturi si functii JavaScript, jQuery si Ajax, cod JavaScript in general.
MarPlo
Administratorul site-ului
Mesaje: 4343

Script Cronometru

Acesta e un script simplu de cronometrare timp care afiseaza zecile de secunda, secundele si minute, facut cu JavaScript. Are optiuni pentru Start, Stop, Reset si poate opri automat cronometrul si sa execute o functie, dupa un anumit timp setat special.
- Poate fi testat la pagina: JavaScript Chronometer / Stopwatch.

Cod: Selectaţi tot

<div id="showtm" style="font-size:21px; font-weight:800;">0:0</div>
<script type="text/javascript"><!--
// chronometer / stopwatch JS script - www.coursesweb.net

// Here set the minutes, seconds, and tenths-of-second when you want the chronometer to stop
// If all these values are set to 0, the chronometer not stop automatically
var stmints = 0;
var stseconds = 0;
var stzecsec = 0;

// function to be executed when the chronometer stops
function toAutoStop() {
  alert('Your life goes on');
}

// the initial tenths-of-second, seconds, and minutes
var zecsec = 0;
var seconds = 0;
var mints = 0;

var startchron = 0;

function chronometer() {
  if(startchron == 1) {
    zecsec += 1;       // set tenths of a second

    // set seconds
    if(zecsec > 9) {
      zecsec = 0;
      seconds += 1;
    }

    // set minutes
    if(seconds > 59) {
      seconds = 0;
      mints += 1;
    }

    // adds data in #showtm
    document.getElementById('showtm').innerHTML = mints+ ' : '+ seconds+ '<sub>'+ zecsec+ '</sub>';

    // if the chronometer reaches to the values for stop, calls whenChrStop(), else, auto-calls chronometer()
    if(zecsec == stzecsec && seconds == stseconds && mints == stmints) toAutoStop();
    else setTimeout("chronometer()", 100);
  }
}

function startChr() { startchron = 1; chronometer(); }      // starts the chronometer
function stopChr() { startchron = 0; }                      // stops the chronometer
function resetChr() {
  zecsec = 0;  seconds = 0; mints = 0; startchron = 0; 
  document.getElementById('showtm').innerHTML = mints+ ' : '+ seconds+ '<sub>'+ zecsec+ '</sub>';
}

// start the chronometer, delete this line if you want to not automatically start the stopwatch
startChr();
--></script>
- Functia startChr() porneste cronometrul.
- Pentru Stop se apeleaza functia stopChr() .
- Pentru Reset se apeleaza functia resetChr() .
Exemplu:

Cod: Selectaţi tot

<button onclick="stopChr()">Stop</button>
<button onclick="resetChr()">Reset</button>

Subiecte similare