หากต้องการหยุดฟังก์ชันระหว่างการดำเนินการ ให้ใช้แนวคิดของ −
document.getElementById().addEventListener().
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<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">Call the function</button>
<button type="button" id="halt">Stop the function execution </button>
<script>
document.getElementById("call").addEventListener("click", callFunction);
document.getElementById("halt").addEventListener("click", haltFunction);
var timeValue = null;
function callFunction() {
timeValue = setInterval(function() {
console.log("The call() is being executed....");
}, 1000);
}
function haltFunction() {
clearInterval(timeValue);
}
</script>
</body>
</html> หากต้องการเรียกใช้โปรแกรมข้างต้น ให้บันทึกชื่อไฟล์ anyName.html(index.html) และคลิกขวาที่ไฟล์และเลือกตัวเลือก open with live server ใน VS code editor
ผลลัพธ์

เมื่อคุณคลิกปุ่มเรียกใช้ฟังก์ชัน ฟังก์ชันจะเรียกใช้ฟังก์ชัน หากต้องการหยุดฟังก์ชัน ให้คลิก หยุดการทำงานของฟังก์ชัน ปุ่ม.
สแนปชอตมีดังนี้ −
