Cara Membuat Stopwatch di JavaScript
Diterbitkan: 2022-02-16
JavaScript stop watch atau lebih tepatnya stop down timer dapat diimplementasikan menggunakan metode pengaturan waktu JavaScript yang dijalankan dalam interval waktu.
Metode pengaturan waktu JavaScript mengotomatiskan tugas tertentu untuk diselesaikan dengan cepat tanpa Anda harus mengklik tombol atau memanggil acara.
Pengaturan waktu JavaScript terdiri dari dua metode utama:
- setTimeout("ekspresi javascript", milidetik);
- clearTimeout( ID setTimeout() );
Saat menggunakan metode pengaturan waktu JavaScript, Anda perlu memahami bagaimana JavaScript mengeksekusi pernyataan dalam interval waktu.
Metode setTimeout()
Sintaksis:
setTimeout( "JavaScript Statements", milliseconds );
Metode pengaturan waktu JavaScript setTimeout() hanya membutuhkan dua parameter:
- parameter pertama: parameter ini adalah pernyataan JavaScript yang ingin Anda jalankan. Nama fungsi string juga dapat diteruskan ke sana.
- parameter kedua: menentukan milidetik yang diperlukan sebelum mengeksekusi pernyataan JavaScript di parameter pertama. Itu hanya dapat disebut sebagai ( Delay On Execution ).
Contoh : Struktur Metode setTimeout()
var setTime = setTimeout( function ( ) { // javascript statements }, 500 ); Or var setTime = setTimeout( "setTimeFunction( )", 500 );
Contoh: Menghitung Milidetik
Untuk bekerja dengan metode pengaturan waktu peristiwa JavaScript, sangat penting bagi Anda untuk memahami cara menghitung milidetik.
Anda memiliki satu detik ( 1 s ) dalam seribu milidetik ( 1000 ms )
Rumus Milidetik
1000ms = 1s Yms = Xs if 1000ms = 1s 300ms = Xs #cross multiplying 1000ms * Xs = 300ms * 1s X * 1000 = 300 * 1 1000X = 300 X = 300 / 1000 X = 0.3s
Ini berarti 300 milidetik = 0,3 detik, tidak sampai satu detik (1 detik). Pernyataan JavaScript Anda akan dieksekusi dalam interval waktu 0,3 detik (0,3 detik).
Membuat Stopwatch
Dengan menggunakan metode event timing JavaScript, kita dapat membuat stop watch kita.
Contoh: Struktur
var clear; function stopWatch( ) { // javascript statement here clear = setTimeout( "stopWatch( )", 1000 ); } Or function stopWatch( ) { // javascript statement here clear = setTimeout( function ( ) { // javascript statement here }, 1000 ); } Or var stopWatch = function ( ) { // javascript statement here clear = setTimeout( "stopWatch( )", 1000 ); }
Contoh: Kode JavaScript untuk startwatch.js
// initialize your variables outside the function var count = 0; var clearTime; var seconds = 0, minutes = 0, hours = 0; var clearState; var secs, mins, gethours ; function startWatch( ) { /* check if seconds is equal to 60 and add a +1 to minutes, and set seconds to 0 */ if ( seconds === 60 ) { seconds = 0; minutes = minutes + 1; } /* you use the javascript tenary operator to format how the minutes should look and add 0 to minutes if less than 10 */ mins = ( minutes < 10 ) ? ( '0' + minutes + ': ' ) : ( minutes + ': ' ); /* check if minutes is equal to 60 and add a +1 to hours set minutes to 0 */ if ( minutes === 60 ) { minutes = 0; hours = hours + 1; } /* you use the javascript tenary operator to format how the hours should look and add 0 to hours if less than 10 */ gethours = ( hours < 10 ) ? ( '0' + hours + ': ' ) : ( hours + ': ' ); secs = ( seconds < 10 ) ? ( '0' + seconds ) : ( seconds ); // display the stopwatch var x = document .getElementById("timer"); x.innerHTML = 'Time: ' + gethours + mins + secs; /* call the seconds counter after displaying the stop watch and increment seconds by +1 to keep it counting */ seconds++; /* call the setTimeout( ) to keep the stop watch alive ! */ clearTime = setTimeout( "startWatch( )", 1000 ); } // startWatch( ) //create a function to start the stop watch function startTime( ) { /* check if seconds, minutes, and hours are equal to zero and start the stop watch */ if ( seconds === 0 && minutes === 0 && hours === 0 ) { /* hide the fulltime when the stop watch is running */ var fulltime = document.getElementById( "fulltime" ); fulltime.style.display = "none"; /* hide the start button if the stop watch is running */ this.style.display = "none"; /* call the startWatch( ) function to execute the stop watch whenever the startTime( ) is triggered */ startWatch( ); } // if () } // startTime() /* you need to bind the startTime( ) function to any event type to keep the stop watch alive ! */ window.addEventListener( 'load', function ( ) { var start = document .getElementById("start"); start.addEventListener( 'click', startTime ); }); // startwatch.js end

Metode clearTimeout()
Untuk menghentikan timer, Anda perlu memanggil metode event waktu clearTimeout() dan ini sangat berguna.
Ini hanya memiliki satu parameter: ID kembali dari metode setTimeout()
Sintaksis:
clearTimeout( return ID of setTimeout() );
Catatan: Metode pengaturan waktu setTimeout() selalu mengembalikan nilai, dan nilai tersebut diteruskan ke metode peristiwa pengaturan waktu clearTimeout().
Parameter ClearTimeout()
var clearTime = setTimeout("Pernyataan JavaScript", 100 );
variabel clearTime dikembalikan sebagai nilai oleh metode pengaturan waktu setTimeout() , yang dapat diteruskan ke clearTimeout( ID ) sebagai ID untuk mereferensikannya - clearTimeout( clearTime );
Bagaimana itu bekerja
Kapanpun metode pengaturan waktu clearTimeout() dipanggil pada metode pengaturan waktu setTimeout() yang aktif, metode pengaturan waktu clearTimeout() akan menghentikan eksekusi metode pengaturan waktu setTimeout() tetapi tanpa merusak eksekusinya sepenuhnya.
Metode pengaturan waktu setTimeout() dibiarkan menganggur selama periode saat metode pengaturan waktu clearTimeout() dipanggil, dan ketika Anda menjalankan kembali metode pengaturan waktu setTimeout(), itu akan dimulai dari titik eksekusinya dihentikan, tidak dimulai dari awal. dari awal.
Sama seperti saat Anda menjeda pemutar media mp3, lalu memutarnya kembali, pemutar akan terus diputar dari posisi sebelumnya, tetapi tidak memulai dari awal.
Sebagai contoh, katakanlah saya memiliki timer berjalan yang dibuat menggunakan metode pengaturan waktu setTimeout(), dan titik awalnya adalah 00. Saya menjalankan timer, dan sekarang membaca 41.
Jika saya memanggil metode pengaturan waktu clearTimeout() pada metode setTimout() aktif ini, itu akan membuatnya menganggur selama periode itu, dan setiap kali saya menjalankan kembali metode pengaturan waktu setTimeout(), itu akan mulai menghitung dari 41, bukan dari 00 .
Untuk membuat penghitung waktu mulai dari 00, Anda harus mengatur ulang penghitungnya. Itulah logikanya.
Contoh: Hentikan Waktu - stopwatch.js
//create a function to stop the time function stopTime( ) { /* check if seconds, minutes and hours are not equal to 0 */ if ( seconds !== 0 || minutes !== 0 || hours !== 0 ) { /* display the full time before reseting the stop watch */ var fulltime = document .getElementById( "fulltime" ); //display the full time fulltime.style.display = "block"; var time = gethours + mins + secs; fulltime.innerHTML = 'Fulltime: ' + time; // reset the stop watch seconds = 0; minutes = 0; hours = 0; secs = '0' + seconds; mins = '0' + minutes + ': '; gethours = '0' + hours + ': '; /* display the stopwatch after it's been stopped */ var x = document.getElementById ("timer"); var stopTime = gethours + mins + secs; x.innerHTML = stopTime; /* display all stop watch control buttons */ var showStart = document.getElementById ('start'); showStart.style.display = "inline-block"; var showStop = document.getElementById ("stop"); showStop.style.display = "inline-block"; /* clear the stop watch using the setTimeout( ) return value 'clearTime' as ID */ clearTimeout( clearTime ); } // if () } // stopTime() /* you need to call the stopTime( ) function to terminate the stop watch */ window.addEventListener( 'load', function ( ) { var stop = document.getElementById ("stop"); stop.addEventListener( 'click', stopTime ); }); // stopwatch.js end
CSS
#stopWatch { width: 280px; height: auto; text-align: center; display: block; padding: 5px; margin: 0 auto; } #timer, #fulltime { width: auto; height: auto; padding: 10px; font-weight: bold; font-family: tahoma; display: block; border: 1px solid #eee; text-align: center; box-shadow: 0 0 5px #ccc; background: #fbfbf0; color: darkblue; border-bottom:4px solid darkgrey; } button { cursor: pointer; font-weight: 700; } #fulltime { display:none; font-size:16px; font-weight:bold; }
HTML
<!DOCTYPE html> <html lang="en"> <head> <title> JavaScript Stop Watch </title> <style text="text/css"> </style> <script type="text/javascript"> </script> </head> <body> <section> <p> Time : 00:00:00 </p> <button> Start </button> <button> Stop </button> <p> </p> </section> </body> </html>
Stopwatch selesai, dan beginilah seharusnya tampilannya.