JavaScript 비동기 처리, Swiper.js 배너, ScrollMagic 활용

My Pale Blue Dot·2025년 2월 20일

JAVASCRIPT

목록 보기
14/26
post-thumbnail

📅 날짜

2025-02-20

📝 학습 내용

오늘은 JavaScript의 비동기 처리(setTimeout, setInterval, Promise, async/await)을 학습하고,
Swiper.js를 활용한 배너 슬라이드, ScrollMagic을 활용한 스크롤 애니메이션 적용을 실습했다.
또한 LoDash의 throttle()을 사용하여 이벤트 최적화 방법도 함께 다루었다.


🎯 1. JavaScript의 비동기 처리 (setTimeout, setInterval)

1️⃣ setTimeout()clearTimeout()을 활용한 비동기 예약 실행 및 취소

👉 setTimeout()을 사용하여 일정 시간이 지난 후 실행되는 동작을 예약하고, clearTimeout()을 이용해 취소할 수 있다.

✅ 예제 코드 (setTimeout / clearTimeout)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setTimeout / clearTimeout</title>
</head>
<body>
    <div class="d1"></div>
    <button onClick="start()">예약실행</button>  <!-- setTimeout 실행 버튼 -->
    <button onClick="stop()">예약취소</button>  <!-- clearTimeout 실행 버튼 -->

    <script>
        let id = null;  // setTimeout의 ID를 저장할 변수

        const start = () => {
            const d1El = document.querySelector('.d1');  // 결과를 표시할 요소 선택

            id = setTimeout(() => {  
                d1El.innerHTML = 'setTimeout 실행 결과!';  // 3초 후에 실행될 코드
            }, 3000);  // 3000ms = 3초 후 실행

            console.log('예약된 setTimeout ID:', id);  // 콘솔에 예약된 setTimeout ID 출력
        };

        const stop = () => {
            clearTimeout(id);  // 예약된 setTimeout 취소
            console.log('setTimeout 예약 취소됨');  // 콘솔에 취소 메시지 출력
        };
    </script>
</body>
</html>

2️⃣ setInterval()clearInterval()을 활용한 반복 실행 및 취소

👉 setInterval()을 사용하면 특정 동작을 일정 간격마다 반복 실행할 수 있으며, clearInterval()을 이용해 중지할 수 있다.

✅ 예제 코드 (setInterval / clearInterval)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setInterval / clearInterval</title>
</head>
<body>
    <div class="d1"></div>
    <button onClick="start()">반복실행</button>  <!-- setInterval 실행 버튼 -->
    <button onClick="stop()">반복취소</button>  <!-- clearInterval 실행 버튼 -->

    <script>
        let id = null;  // setInterval의 ID를 저장할 변수
        let cnt = 0;    // 카운트 변수

        const start = () => {
            const d1El = document.querySelector('.d1');  // 결과를 표시할 요소 선택

            id = setInterval(() => {  
                d1El.innerHTML = `카운트: ${++cnt}`;  // 1초마다 cnt 증가 후 화면에 표시
            }, 1000);  // 1000ms = 1초 간격

            console.log('setInterval 실행 중, ID:', id);  // 콘솔에 실행 메시지 출력
        };

        const stop = () => {
            clearInterval(id);  // 실행 중인 setInterval 중지
            console.log('setInterval 중지됨');  // 콘솔에 중지 메시지 출력
        };
    </script>
</body>
</html>

🎯 2. Swiper.js를 활용한 배너 슬라이드

✅ Swiper.js 설정 및 적용

👉 Swiper.js는 웹사이트에서 다양한 슬라이드 배너를 쉽게 구현할 수 있는 라이브러리이다.

✅ 예제 코드 (Swiper.js 슬라이드 배너)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Swiper.js 배너</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
</head>
<body>
    <div class="swiper">
        <div class="swiper-wrapper">
            <div class="swiper-slide">Slide 1</div>  <!-- 첫 번째 슬라이드 -->
            <div class="swiper-slide">Slide 2</div>  <!-- 두 번째 슬라이드 -->
            <div class="swiper-slide">Slide 3</div>  <!-- 세 번째 슬라이드 -->
        </div>
        <div class="swiper-pagination"></div>  <!-- 페이지네이션 -->
        <div class="swiper-button-prev"></div>  <!-- 이전 버튼 -->
        <div class="swiper-button-next"></div>  <!-- 다음 버튼 -->
    </div>

    <script>
        const swiper = new Swiper('.swiper', {
            direction: 'horizontal',  // 가로 방향 슬라이드
            autoplay: { delay: 2000 },  // 2초마다 자동 전환
            loop: true,  // 무한 반복 설정
            effect: "slide",  // 슬라이드 효과 적용
            pagination: { el: '.swiper-pagination', clickable: true },  // 페이지네이션 활성화
            navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },  // 네비게이션 버튼 활성화
        });
    </script>
</body>
</html>

🎯 3. ScrollMagic을 활용한 스크롤 애니메이션

✅ 특정 요소가 화면 중앙에 도달하면 애니메이션 적용

👉 ScrollMagic을 사용하면 특정 요소가 스크롤에 의해 화면의 특정 위치에 도달했을 때 애니메이션을 적용할 수 있다.

✅ 예제 코드 (ScrollMagic 활용)

const spyedEl = document.querySelector('.scroll-spy');  // 감시할 요소 선택
const ballEl = document.querySelector('.scroll-spy .ball');  // 애니메이션 적용할 요소

const scrollMagicObj = new ScrollMagic.Scene({
    triggerElement: spyedEl,  // 감시할 요소 지정
    triggerHook: 0.5,  // 스크롤 위치 (0: 최상단, 0.5: 중앙, 1: 최하단)
})
.setClassToggle(ballEl, 'move')  // 특정 클래스('move')를 추가하여 애니메이션 적용
.addTo(new ScrollMagic.Controller());  // ScrollMagic 컨트롤러에 추가하여 실행

🤔 느낀 점

  • 비동기 처리 (setTimeout, setInterval, Promise, async/await)을 활용하여 동작을 제어하는 방법을 익혔다.
  • Swiper.js를 활용하면 쉽고 빠르게 배너 슬라이드를 구현할 수 있다.
  • ScrollMagic을 사용하여 스크롤 이벤트 기반 애니메이션을 적용할 수 있다.
profile
Here, My Pale Blue.🌏

0개의 댓글