목차


 1 ~ 5를 1초마다 콘솔에 출력

let i = 1;
const tInterval = setInterval( () => { 
    console.log( i ); 
    i++; 
    if( i > 5 ) { 
        clearInterval( tInterval ); 
    } 
}, 1000 );

 

 현재 시각을 출력한뒤, 멈춤 버튼을 누르면 멈추고, 재시작 버튼을 누르면 재시작

<h1 id="nowTime">시간 로딩중...</h1>
<button type="button" id="stopBtn">STOP</button>
<button type="button" id="startBtn">START</button>
const span = document.getElementById( "nowTime" );
function getTime(){
    const time = new Date();
    const hour = String( time.getHours() ).padStart( 2, "0" );
    const pmHour = String( time.getHours() - 12 ).padStart( 2, "0" );
    const minutes = String( time.getMinutes() ).padStart( 2, "0" );
    const seconds = String( time.getSeconds() ).padStart( 2, "0" );

    if( hour > 12 ) {
        span.innerHTML = "오후 " + pmHour + " : " + minutes + " : " + seconds;
    } else {
        span.innerHTML = "오전 " + hour + " : " + minutes + " : " + seconds;
    }
}
let a = setInterval( getTime, 1000 );

// 멈춤 버튼
const stopBtn = document.getElementById( 'stopBtn' );
stopBtn.addEventListener( "click", () => clearInterval( a ) );

// 재시작 버튼
const startBtn = document.getElementById( 'startBtn' );
startBtn.addEventListener( "click", () => a = setInterval( getTime, 1000 ) );

 

Github

Link

 

'JavaScript > JavaScript_TEST' 카테고리의 다른 글

Ajax_TEST  (0) 2023.05.10
promise_TEST  (0) 2023.05.09
DOM_TEST  (0) 2023.05.05
date_TEST  (0) 2023.05.05
math_TEST  (0) 2023.05.05

+ Recent posts