PlusMagi's Blog By Pitt Phunsanit

แก้ setInterval ทำงานช้าไม่ยอมจบ

สาเหตุคือ เมื่อใส่ setInterval ลงไปใน recursive function มันจะเรียกตัวเองและสร้าง setInterval ขึ้นมาเรื่อย ๆ ไม่ยอมหยุด ตามตัวอย่าง

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>bad recursive By Pitt Phunsanit</title>
</head>
<body>
<textarea id="log" cols="100" rows="50"></textarea>
<script>
log = document.getElementById ('log') ;
function recursive (a) { /* ค่าไว้อ้างอิง */ intervalId = setInterval (function () { log.value = log.value + 'n recursive a = '+a; if (a < 10) { a++; recursive (a) ; }else{ clearInterval (intervalId) ; log.value = log.value + 'n จบที่ครั้งที่ 10 ? '; } } ,1000) ;
}
recursive (0) ;
</script>
</body>
</html>
</script>
</body>
</html>

จะเห็นว่า a = 2 มีมากกว่า 1 ครั้งพอรอบต่อ ๆ มายิ่งมีจำนวนมากขึ้นเรื่อย ๆ ขนาดเกินเงื่อนไขให้หยุดทำงาน ก็ยังไม่หยุด แก้ได้โดยเพิ่มเงื่อนไขในการเรียกตัวเองตามตัวอย่าง

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>recursive Structure By Pitt Phunsanit</title>
</head>
<body>
<textarea id="log" cols="100" rows="50"></textarea>
<script>
log = document.getElementById ('log') ;
var intervalId;
/* ต้องอยู่นอก recursive function */
function recursive (a) { /* กันเรียกซ้ำ */ if (typeof intervalId != "number") { /* ค่าไว้อ้างอิง */ intervalId = setInterval (function () { log.value = log.value + 'n recursive a = '+a; if (a < 10) { a++; recursive (a) ; }else{ clearInterval (intervalId) ; log.value = log.value + 'n จบที่ครั้งที่ 10 ? '; } } ,1000) ; }
}
recursive (0) ;
</script>
</body>
</html>
Exit mobile version