
📅 2025-09-25
➡️ JavaScript 이벤트와 타이머에 대해 새롭게 알게 된 것 또는 헷갈리는 부분 정리
<div onclick="alert('div 클릭!')">
<button onclick="alert('button 클릭!')">클릭해보세요</button>
</div>이벤트 전파 흐름은 3단계로 구분
1단계: 캡처링 (Capturing) → 위에서 아래로
2단계: 타깃 (Target) → 실제 클릭한 요소
3단계: 버블링 (Bubbling) → 아래에서 위로
<form onclick="alert('form')">FORM
<div onclick="alert('div')">DIV
<p onclick="alert('p')">P</p>
</div>
</form><p>클릭 시 실행 순서 : p → div → form 순으로 이벤트 발생주요 메서드
event.stopPropagation()
event.stopImmediatePropagation()
event.preventDefault()
실습
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: gray;
opacity: 0.8;
/* 추가 */
display: none;
padding-top: 100px;
}
.modal-content {
width: 200px;
height: 200px;
background-color: white;
padding: 20px;
margin: auto;
}
/* 추가 */
.show {
display: block;
}
</style>
</head>
<body>
<div>본문</div>
<button class="modal-btn">모달열기</button>
<div class="modal">
<div class="modal-content">
<!-- <form> -->
<input class="아이디" type="text" placeholder="아이디" />
<input class="비밀번호" type="password" placeholder="비밀번호" />
<button class="login">로그인하기</button>
<button class="close-btn">닫기</button>
<!-- </form> -->
</div>
</div>
<script src="script2.js"></script>
</body>
</html>
const modal = document.querySelector('.modal');
const modalBtn = document.querySelector('.modal-btn');
const closeBtn = document.querySelector('.close-btn');
const openModal = () => {
modal.classList.toggle('show');
};
modalBtn.addEventListener('click', openModal);
closeBtn.addEventListener('click', openModal);
modal.addEventListener('click', (e) => {
// console.log(e.target);
// console.log(e.currentTarget);
console.log('modal click');
if (e.target === modal) {
modal.classList.remove('show');
}
});
setTimeout(실행할함수, 지연시간ms, ...추가인자);실행할함수 : 지연시간 후 실행될 콜백 함수
지연시간ms : 밀리초(ms) 단위 (1000 = 1초)
setTimeout(() => {
console.log("3초 뒤 실행!");
}, 3000);
setInterval(실행할함수, 간격ms, ...추가인자);실행할함수 : 반복 실행될 콜백 함수
간격ms : 반복 주기 (밀리초)
setInterval(() => {
console.log("1초마다 실행!");
}, 1000);
멈추기 (clear 함수)
setTimeout / setInterval은 id(숫자)를 반환clearTimeout / clearInterval에 넘기면 멈출 수 있음const timerId = setInterval(() => {
console.log("반복 중...");
}, 1000);
// 5초 후에 멈추기
setTimeout(() => {
clearInterval(timerId);
console.log("반복 종료");
}, 5000);
setInterval와 clearInterval는 한 세트라고 기억하자!❗ 정확한 타이밍은 보장이 안됨
- 자바스크립트는 싱글 스레드여서 다른 코드가 실행중이면 지연될 수 있음
- 1000ms 설정해도 실제 실행은 1000ms + a
❗
setInterval보단setTimeout반복이 더 안전함
setInterval은 콜백 시간이 많이 길어져도 무시하고 일정 주기로 계속 호출함- 때문에 콜백이 밀리거나 중첩 실행되면 불필요하게 CPU 자원을 점유할 수 있음