JavaScript에서 스톱워치를 만드는 방법

게시 됨: 2022-02-16
JavaScript에서 스톱워치를 만드는 방법

JavaScript 스톱워치 또는 스톱다운 타이머는 시간 간격으로 실행되는 JavaScript 타이밍 방법을 사용하여 구현할 수 있습니다.

JavaScript 타이밍 방법은 버튼을 클릭하거나 이벤트를 호출할 필요 없이 즉석에서 수행할 특정 작업을 자동화합니다.

JavaScript 타이밍은 두 가지 주요 방법으로 구성됩니다.

  • setTimeout( "자바스크립트 표현식", 밀리초 );
  • clearTimeout( setTimeout( ) 의 ID );

JavaScript 타이밍 방법을 사용할 때 JavaScript가 시간 간격으로 명령문을 실행하는 방법을 이해해야 합니다.

setTimeout() 메서드

통사론:

 setTimeout( "JavaScript Statements", milliseconds );

setTimeout( ) JavaScript 타이밍 메서드는 두 개의 매개변수만 사용합니다.

  • 첫 번째 매개변수: 이 매개변수는 실행하려는 JavaScript 문입니다. 문자열 함수 이름을 전달할 수도 있습니다.
  • 두 번째 매개변수: 첫 번째 매개변수에서 JavaScript 문을 실행하기 전에 걸리는 시간(밀리초)을 지정합니다. 간단히 ( Delay On Execution )이라고 할 수 있습니다.

예 : setTimeout( ) 메소드의 구조

 var setTime = setTimeout( function ( ) { // javascript statements }, 500 ); Or var setTime = setTimeout( "setTimeFunction( )", 500 );

예: 밀리초 계산

JavaScript 이벤트 타이밍 방법을 사용하려면 밀리초를 계산하는 방법을 이해하는 것이 매우 중요합니다.

1,000밀리초(1000ms)는 1초(1s)입니다.

밀리초 공식

 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

이것은 300밀리초 = 0.3초를 의미하며 최대 1초(1초)가 아닙니다. JavaScript 문은 0.3초(0.3초)의 시간 간격으로 실행됩니다.

스톱워치 만들기

JavaScript 타이밍 이벤트 메서드를 사용하여 스톱워치를 만들 수 있습니다.

예: 구조

 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 ); }

예: startwatch.js용 JavaScript 코드

 // 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

clearTimeout( ) 메서드

타이머를 중지하려면 clearTimeout( ) 타이밍 이벤트 메서드를 호출해야 하며 이는 매우 편리합니다.

그것은 단지 하나의 매개변수를 가지고 있습니다: setTimeout() 메소드의 리턴 ID

통사론:

 clearTimeout( return ID of setTimeout() );

참고: setTimeout( ) 타이밍 메서드는 항상 값을 반환하고 해당 값은 clearTimeout( ) 타이밍 이벤트 메서드로 전달됩니다.

ClearTimeout( ) 매개변수

var clearTime = setTimeout( "자바스크립트 문", 100 );

clearTime 변수는 setTimeout( ) 타이밍 메서드에 의해 값으로 반환되며, 이를 참조하는 ID로 clearTimeout( ID )에 전달할 수 있습니다. - clearTimeout( clearTime );

작동 원리

활성 상태인 setTimeout( ) 타이밍 메서드에서 clearTimeout( ) 타이밍 메서드가 호출될 때마다 clearTimeout( ) 타이밍 메서드는 setTimeout( ) 타이밍 메서드의 실행을 중지하지만 실행을 완전히 파괴하지는 않습니다.

setTimeout() 타이밍 메서드는 clearTimeout() 타이밍 메서드가 호출되는 동안 유휴 상태로 유지되며 setTimeout() 타이밍 메서드를 다시 실행하면 실행이 중지된 지점부터 시작됩니다. 처음부터.

mp3 미디어 플레이어를 일시 중지했다가 다시 재생할 때와 마찬가지로 이전 위치에서 계속 재생되지만 처음부터 다시 시작하지는 않습니다.

예를 들어, setTimeout( ) 타이밍 메서드를 사용하여 만든 실행 중인 타이머가 있고 시작점이 00이라고 가정해 보겠습니다. 타이머를 실행했는데 현재 41을 읽고 있습니다.

이 활성 setTimout() 메서드에서 clearTimeout() 타이밍 메서드를 호출하면 해당 기간 동안 유휴 상태가 되고 setTimeout() 타이밍 메서드를 다시 실행할 때마다 00이 아니라 41부터 계산을 시작합니다. .

타이머가 00부터 시작되도록 하려면 카운터를 재설정해야 합니다. 그게 논리야.

예: 시간을 멈춰라 - 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>

스톱워치가 완성되고 이것이 보여야 합니다.

시작 및 중지 버튼이 있는 작은 타이머