반응형
웹 개발에서 특정 작업을 주기적으로 수행하거나, 일정 시간 간격으로 사용자를 위한 알림을 제공하는 기능은 다양한 상황에서 유용하게 활용됩니다. 이를 구현하기 위해 JavaScript와 HTML을 조합하여 간단한 시스템을 구축할 수 있습니다. 이번 글에서는 setInterval
과 Notification API
를 사용하여 일정 시간마다 특정 조건을 확인하고 알림을 띄우는 방법을 자세히 설명하겠습니다.
1. 스크립트 개요 및 작동 원리
목표: 일정 시간마다 작업을 수행하고, 조건을 만족하면 알림을 사용자에게 띄우는 기능을 구현.
1.1 활용 사례
- 실시간 주식 가격 알림
- 채팅 애플리케이션의 새 메시지 알림
- 사용자의 작업을 리마인드하는 알림 기능
1.2 주요 기술
setInterval
: 주어진 시간 간격마다 특정 작업을 실행.Notification API
: 브라우저에서 데스크톱 알림을 띄우는 기능.- 조건 체크: 특정 조건에 따라 알림을 띄울지 결정.
2. 기본적인 코드 구성
2.1 HTML 기본 구조
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notification Demo</title>
</head>
<body>
<h1>스크립트를 사용한 알림 시스템</h1>
<p>이 페이지는 일정 시간마다 작업을 체크하고 알림을 제공합니다.</p>
<button id="startBtn">알림 시작</button>
<button id="stopBtn">알림 중지</button>
<script src="script.js"></script>
</body>
</html>
설명:
startBtn
: 알림 기능을 시작하는 버튼.stopBtn
: 알림 기능을 중지하는 버튼.script.js
: JavaScript 코드가 포함된 외부 파일.
3. JavaScript 코드 작성
3.1 기본 알림 띄우기
// 브라우저 알림 권한 요청
function requestNotificationPermission() {
if (Notification.permission === 'default') {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('알림 권한이 허용되었습니다.');
} else {
console.log('알림 권한이 거부되었습니다.');
}
});
}
}
// 알림 띄우기 함수
function showNotification(title, body) {
if (Notification.permission === 'granted') {
new Notification(title, { body });
} else {
console.log('알림 권한이 없습니다.');
}
}
// 초기화
requestNotificationPermission();
설명:
Notification.requestPermission
: 알림 권한을 요청.new Notification
: 알림을 생성하고 띄움.
3.2 일정 시간마다 체크 및 알림 띄우기
let intervalId;
// 특정 조건을 확인하는 함수
function checkCondition() {
const randomNumber = Math.floor(Math.random() * 10); // 0~9 사이의 랜덤 숫자 생성
console.log(`랜덤 숫자: ${randomNumber}`);
if (randomNumber > 7) {
showNotification('알림', `랜덤 숫자가 7보다 큽니다: ${randomNumber}`);
}
}
// 알림 시작
function startNotifications() {
if (!intervalId) {
intervalId = setInterval(checkCondition, 5000); // 5초마다 실행
console.log('알림 기능이 시작되었습니다.');
}
}
// 알림 중지
function stopNotifications() {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
console.log('알림 기능이 중지되었습니다.');
}
}
// 이벤트 리스너 등록
document.getElementById('startBtn').addEventListener('click', startNotifications);
document.getElementById('stopBtn').addEventListener('click', stopNotifications);
설명:
checkCondition
: 조건을 확인하여 알림을 띄움.setInterval
: 5초마다checkCondition
호출.clearInterval
: 알림 중지.
3.3 사용자 경험 개선: 알림 시간 표시
function showNotificationWithTime() {
const currentTime = new Date().toLocaleTimeString();
showNotification('현재 시간', `지금 시간은 ${currentTime}입니다.`);
}
// 알림에 시간 포함하기
function startTimeNotifications() {
if (!intervalId) {
intervalId = setInterval(showNotificationWithTime, 60000); // 1분마다 실행
console.log('시간 알림이 시작되었습니다.');
}
}
설명:
Date().toLocaleTimeString
: 현재 시간을 사용자 친화적으로 표시.
4. 추가 기능: 알림 카운터 및 종료 조건
4.1 알림 카운터
let notificationCount = 0;
function checkConditionWithCount() {
if (notificationCount >= 10) {
stopNotifications();
alert('알림이 10회 이상 발생하여 중지되었습니다.');
return;
}
const randomNumber = Math.floor(Math.random() * 10);
if (randomNumber > 7) {
notificationCount++;
showNotification('알림', `랜덤 숫자가 7보다 큽니다: ${randomNumber}`);
}
}
설명:
notificationCount
: 알림 횟수를 추적.- 조건 충족 시 알림 횟수를 증가.
4.2 종료 조건: 특정 시간 이후 알림 종료
function stopNotificationsAfterTimeout(timeout) {
setTimeout(() => {
stopNotifications();
alert('설정된 시간이 경과하여 알림이 종료되었습니다.');
}, timeout);
}
// 알림 시작 시 30초 후 종료 설정
startNotifications();
stopNotificationsAfterTimeout(30000); // 30초 후 종료
설명:
setTimeout
: 알림을 지정된 시간 후 자동 종료.
5. 통합 코드
아래는 위에서 설명한 기능을 모두 포함한 완전한 코드입니다.
let intervalId;
let notificationCount = 0;
// 알림 권한 요청
function requestNotificationPermission() {
if (Notification.permission === 'default') {
Notification.requestPermission();
}
}
// 알림 띄우기
function showNotification(title, body) {
if (Notification.permission === 'granted') {
new Notification(title, { body });
}
}
// 조건 확인 및 알림
function checkCondition() {
if (notificationCount >= 10) {
stopNotifications();
alert('알림이 10회 이상 발생하여 중지되었습니다.');
return;
}
const randomNumber = Math.floor(Math.random() * 10);
if (randomNumber > 7) {
notificationCount++;
showNotification('알림', `랜덤 숫자: ${randomNumber}`);
}
}
// 알림 시작
function startNotifications() {
if (!intervalId) {
intervalId = setInterval(checkCondition, 5000); // 5초마다 실행
}
}
// 알림 중지
function stopNotifications() {
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
}
// 권한 요청 및 이벤트 등록
requestNotificationPermission();
document.getElementById('startBtn').addEventListener('click', startNotifications);
document.getElementById('stopBtn').addEventListener('click', stopNotifications);
6. 결과 화면과 브라우저 권한 처리
- 결과: 버튼을 눌러 알림을 시작하고, 특정 조건이 충족되면 알림이 표시됩니다.
- 브라우저 권한: 사용자는 알림 권한을 허용해야 알림이 정상 작동합니다.
7. 마무리
위의 예제는 웹 브라우저 환경에서 스크립트를 활용하여 주기적으로 작업을 체크하고, 조건에 따라 알림을 띄우는 방법을 보여줍니다. 이를 확장하여 사용자 정의 작업이나 데이터베이스와 연동된 알림 시스템을 개발할 수도 있습니다.
이 글을 참고하여 여러분의 프로젝트에 알림 시스템을 구현해 보세요!
반응형
'개발 > Javascript' 카테고리의 다른 글
실시간 채팅 시스템 구현: JavaScript와 WebSocket 활용 (0) | 2025.01.19 |
---|---|
스크롤 방향에 따라 상단 메뉴를 동적으로 표시하는 방법 (0) | 2025.01.19 |
웹 저장소 기술: SessionStorage, LocalStorage, 쿠키의 비교 및 사용법 (0) | 2025.01.14 |
다중 모니터 환경에서 window.open으로 특정 모니터에 팝업 띄우기 (0) | 2025.01.14 |
JQuery로 구현하는 동적 콤보박스 연결 예제 (0) | 2025.01.14 |