far

[Javascript] 연속된 클릭 막기 본문

Javascript

[Javascript] 연속된 클릭 막기

Eater 2023. 4. 6. 21:16

작업을 하다 전송 버튼을 연타하면 데이터를 받아올 때 꼬이는 현상이 나타나는걸 발견했다. 이런 경우 클릭을 연속해서 할 수 없도록 막아버리는게 최선의 방법이라고 생각했다.

 

index.html

<button id="langBtn" type="button">
    <i class="gg-arrows-exchange"></i>
</button>

<!-- 생략 -->

<div class="translateSelect__area">
    <div style="margin-top: 10px;"></div>
    <pre id="result"></pre>
</div>

HTML은 설명에 필요한 부분만 남겼다.

 

translate.js

const langBtn = document.getElementById('langBtn');
const result = document.getElementById('result');

//...

let clickable = true;
langBtn.addEventListener("click", () => {
    if (clickable === true && result.textContent !== '') {
        clickable = false

        resultTranslate() // API 연결 함수 (생략)
        
        setTimeout(() => {
            clickable = true
        }, 300)
    }
});

먼저 clickable이라는 변수를 만들어 boolean값을 선언하고 이벤트리스너 내부에 if문을 만든다. if문을 통과하면 clickable을 바로 false로 바꿔주고 데이터를 서버로 전송한 뒤 setTimeout함수를 사용해 true로 바꿔준다. 그러면 이제 전송 버튼을 연타해도 0.3가 지나기 전에는 서버로 데이터를 전송 할 수 없게 된다.

Comments