<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax로 파일로드 및 setTimeOut 사용방법</title>
<style>
.box{
width: 100px;
height: 30px;
color: white;
background-color: black;
text-align: center;
line-height: 30px;
font-size: 12px;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<input type="button" value="실행" onclick="gopage()">
<div id="ag">
</div>
<div id="ag2">
</div>
</body>
<script>
//광고스킵 만들기
var time = 5; //카운팅 숫자
function aaa() {
document.getElementById("box").innerText = "광고중" + time + "초";
time--; //1씩 감소
if(time >= 0){
setTimeout(aaa,1000); //해당 메소드를 재호출
}else{ //0이하가 되었을경우 해당 단어로 오브젝트에 출력
document.getElementById("box").innerText = "SKIP";
}
}
setTimeout(aaa,1000); //페이지가 실행되고 1초 후 aaa 함수 호출
//외부 api를 이용시 로딩 기다릴때 사용
function gopage(){
var url = "http://naver.com";
//setTimeout 함수 추가적인 핸들링 이벤트가 발생하는 코드가 있을 경우
setTimeout(function(){
location.href = url;
},5000);
//5초 후에 이동
}
//setTimeout(gopage,3000);
//1000 = 1초 setTimeout은 해당 범위의 시간이 지난 후 작동
//약관출력에 사용
//ajax I/O 형태로 파일을 로드하여 해당 내용을 HTML에 출력하는 방식
window.onload = function(){
var http = new XMLHttpRequest; //ajax 통신
//다른곳에있는 파일은 못가져오고 나한테 있는 파일만 사용가능
//파일 로드해야해서 GET !
//txt파일 저장할때 파일 인코딩이 utf-8로 되어있지않으면 다깨져서 보임 주의 !
http.open("GET","./realty/agree1.txt",false); //GET 통신을 이용하여 해당 파일을 로드
http.send(); //통신 실행
document.getElementById("ag").innerHTML = http.response; //HTML에 내용을 출력
//var http2 = new XMLHttpRequest;
http.open("GET","./realty/agree2.txt",false);
http.send();
document.getElementById("ag2").innerHTML = http.response;
}
</script>
</html>
광고 스킵 기능
var time = 5 // 카운팅 숫자 초기화
function aaa() {
document.getElementById("box").innerText = "광고중 " + time + "초"
time-- // 시간 1씩 감소
if (time >= 0) {
setTimeout(aaa, 1000) // 1초 후 다시 aaa 함수 호출
} else {
document.getElementById("box").innerText = "SKIP" // 카운팅이 끝나면 "SKIP" 출력
}
}
setTimeout(aaa, 1000) // 페이지가 로드된 후 1초 뒤 aaa 함수 실행
- 간단한 카운트다운 타이머를 구현
- setTimeout을 재귀적으로 호출하여, 매 초마다 카운트가 감소함 시간이 0이 되면 "SKIP"이라는 메시지를 표시
외부 페이지로 이동
function gopage() {
var url = "http://naver.com" // 이동할 URL 설정
setTimeout(function() {
location.href = url // 5초 후 페이지 이동
}, 5000)
}
- gopage 함수는 버튼 클릭 시 특정 URL로 이동하기 전에 대기 시간을 부여
- 외부 API 호출 시 로딩 화면을 제공하거나, 사용자에게 대기 시간을 안내할 때 유용
Ajax로 약관 파일 로드
window.onload = function() {
var http = new XMLHttpRequest() // Ajax 객체 생성
// 첫 번째 약관 파일 로드
http.open("GET", "./realty/agree1.txt", false)
http.send()
document.getElementById("ag").innerHTML = http.response
// 두 번째 약관 파일 로드
http.open("GET", "./realty/agree2.txt", false)
http.send()
document.getElementById("ag2").innerHTML = http.response
}
- XMLHttpRequest 객체를 사용하여 로컬 서버의 텍스트 파일을 로드함
- 파일 인코딩은 반드시 UTF-8로 설정해야 함 그렇지 않으면 한글이 깨질 수 있음
- 두 개의 약관 파일(agree1.txt, agree2.txt)을 로드하여 각각 다른 HTML 요소에 표시함
➕
- setTimeout과 setInterval 차이
- setTimeout: 지정된 시간이 지난 후 한 번만 실행
- setInterval: 지정된 시간 간격으로 반복 실행
- Ajax 사용 시 주의점
- 로컬 파일을 로드할 때, 브라우저 보안 설정에 따라 동작이 제한될 수 있음 이를 방지하려면 로컬 서버를 실행해야 함
- 최신 비동기 방식으로는 fetch API를 사용하는 것이 권장됨