yuzunsang / JS-deep-dive-study

자바스크립트 딥 다이브 스터디✨
0 stars 3 forks source link

[CH41]타이머 #53

Open yuzunsang opened 2 months ago

yuzunsang commented 2 months ago

[퀴즈 예시] Q. 여기에 퀴즈 설명을 적으세요.

적을 코드가 있다면 밑에 적어주세요. (백틱 3개로 코드를 감싸면 코드 양식을 적을 수 있습니다.)

// 예시 코드
const arr = [1, 2, 3];
console.log("Hello");

아래 코드를 복붙해서 정답을 적어주세요.

<details>
    <summary>정답</summary>
    <div markdown="1">    
    정답 설명
    </div>
</details>
yuzunsang commented 1 month ago

[주석에 hint가 있습니다] Q1. 검색 입력 필드 이벤트 핸들러에 디바운스 기법을 적용한 코드 중 일부입니다. 빈칸에 들어갈 코드는 무엇일까요?

const debounce = (callback, delay) => {
    let timerId;

    return (...args) => {
    // delay가 경과하기 이전에 이벤트가 발생하면 이전 타이머를 취소합니다
    if (timerId) 🟨;

    // 새로운 타이머를 재설정합니다
    🟦 = setTimeout(callback, delay, ...args);
    };
};

$input.oninput = debounce(e => {
    $msg.textContent = e.target.value;
}, 300);

[주석에 hint가 있습니다] Q2. scroll 이벤트 핸들러에 스로틀 기법을 적용한 코드 중 일부입니다. 빈칸에 들어갈 코드는 무엇일까요?

const throttle = (callback, delay) => {
    let timerId;

    return (...args) => {
        // delay가 경과하기 이전에 이벤트가 발생하면 아무것도 하지 않습니다
        if (timerId) 🟨;

        // delay가 경과했을 때 이벤트가 발생하면 새로운 타이머를 재설정합니다
        timerId = setTimeout(() => {
            callback(...args);
            // 타이머가 완료된 후 다음 이벤트 핸들링을 위해 타이머를 초기화해줍니다
            timerId = 🟦;
        }, delay);
    };
};

let throttleCount = 0;

$container.addEventListener('scroll', throttle(() => {
    $throttleCount.textContent = ++throttleCount;
}, 100));
정답
1번 정답: 🟨 clearTimeout(timerId) 🟦timerId

2번 정답: 🟨 return 🟦null
(참고) clearTimeout은 타이머가 동작 중일 때만 효과가 있으며 타이머가 완료된 이후는 null로 초기화하는 것이 옳습니다.
bo-eun commented 1 month ago

Q. 아래는 1초마다 count값이 증가하는 함수입니다. count가 5보다 클 때 intervalld함수를 멈추도록 함수를 수정해주세요.

let count = 0;

const intervalId = setInterval(function() {
    count++;

}, 1000);
정답
let count = 0; const intervalId = setInterval(function() { count++; if( count > 5 ) { clearInterval(intervalId); } }, 1000);
J-yun-ji commented 1 month ago

Q. 짧은 시간 간격으로 연속해서 발생하는 이벤트를 그룹화하여 과도한 이벤트 핸들러 호출을 방지하는 프로그래밍 기법 2가지는 무엇인가요 ?

정답
디바운스, 스로틀