Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 실행 중인 함수를 중지하는 방법 완벽 가이드

JavaScript에서 실행 중인 함수를 중지하려면 document.getElementById().addEventListener() 개념을 활용하면 됩니다. 핵심 아이디어는 버튼 클릭 이벤트로 함수를 시작하고, 다른 버튼의 클릭 이벤트에서 clearInterval()을 호출하여 반복 실행을 멈추는 것입니다.

setInterval()은 지정한 시간 간격마다 함수를 반복 실행하며, 반환된 ID 값을 clearInterval()에 전달하면 해당 반복이 즉시 중단됩니다.

예제 코드

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<button type="button" id="call">함수 호출</button>
<button type="button" id="halt">함수 실행 중지</button>
<script>
    document.getElementById("call").addEventListener("click", callFunction);
    document.getElementById("halt").addEventListener("click", haltFunction);
    var timeValue = null;
    function callFunction() {
        timeValue = setInterval(function() {
            console.log("call() 함수가 실행되고 있습니다....");
        }, 1000);
    }
    function haltFunction() {
        clearInterval(timeValue);
    }
</script>
</body>
</html>

코드 설명

  • callFunction(): '함수 호출' 버튼을 클릭하면 setInterval()이 1초(1000ms)마다 콘솔에 메시지를 출력합니다.
  • haltFunction(): '함수 실행 중지' 버튼을 클릭하면 저장해 둔 타이머 ID를 이용해 clearInterval()이 반복 실행을 종료합니다.

프로그램 실행 방법

위 프로그램을 실행하려면 파일 이름을 anyName.html(index.html)로 저장한 뒤, VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 'Open with Live Server' 옵션을 선택하세요.

실행 결과

JavaScript에서 실행 중인 함수를 중지하는 방법 완벽 가이드

'함수 호출' 버튼을 클릭하면 함수가 실행되어 1초마다 콘솔에 메시지가 출력됩니다. 함수를 중지하려면 '함수 실행 중지' 버튼을 클릭하면 됩니다.

아래는 '함수 실행 중지' 버튼을 클릭했을 때의 화면입니다.

JavaScript에서 실행 중인 함수를 중지하는 방법 완벽 가이드