상세 컨텐츠

본문 제목

[JS] Clock

Java Script

by (방울)도마토 2023. 10. 18. 13:43

본문

1. setIntervals(funcName, timeDelay)

- 특정 시간 마다 반복적으로 함수를 시행함

- repeatedly calls a function or executes a code snippet, with a fixed time delay between each call (in mdn)

- time delay는 ms 단위로 적어줌 

const clock = document.querySelector("h2#clock")

function sayHello() {
    console.log("Hello");    
}

setInterval(sayHello, 5000); 
	// 5초마다 'sayHello' 함수를 호출함

 

 

 

 

 

2. setTimeout(funcName, timeDelay)

- 시간을 설정하여 지정된 함수를 호출 

- sets a timer which executes a function or specified piece of code once the timer expires (in mdn)

const clock = document.querySelector("h2#clock")

function sayHello() {
    console.log("Hello");    
}

setTimeout(sayHello, 5000); 
	// 5초 후 'sayHello' 함수를 호출함

3. Date object

- 날짜를 저장하거나 날짜와 관련된 메서드 제공 

- 매초 마다 새로운 object 생성 

const clock = document.querySelector("h2#clock")

function getClock() {
    const date = new Date() // 새로운 Date 객체 생성 
    console.log(`${date.getHours()} : ${date.getMinutes()} : ${date.getSeconds()}`);    
}

setInterval(getClock, 1000);

반복은 setInterval을 통해

 

4. padString(문자열 길이, 시작한 다른 문자열)

- 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열 반환

"1".padStart(2, '0')
	// 문자열의 길이가 2를 충족하지 않으면, 
   	// 문자열 앞에 '0'을 배치

const clock = document.querySelector("h2#clock")

function getClock() {
    const date = new Date() // 새로운 Date 객체 생성 
    const hours = String(date.getHours()).padStart(2, '0');
        // getHours()는 number을 반환하므로 padStart()을 사용할 수 없음
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    clock.innerText = (`${hours} : ${minutes} : ${seconds}`);    
}

getClock()
setInterval(getClock, 1000);

'Java Script' 카테고리의 다른 글

[JS]Quotes and Background_Math.random(), createElement()  (0) 2023.10.18
[JS]03. Login 2  (1) 2023.10.10
[JS]03. Login 1  (0) 2023.10.10
[JS]02. JavaScript on the Browser 3  (0) 2023.10.07
[JS]02. JavaScript on the Browser 2  (0) 2023.10.07

관련글 더보기

댓글 영역