สาเหตุคือ เมื่อใส่ setInterval ลงไปใน recursive function มันจะเรียกตัวเองและสร้าง setInterval ขึ้นมาเรื่อยๆ ไม่ยอมหยุด ตามตัวอย่าง
[sourcecode language=”html”]
<!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>
[/sourcecode]
จะเห็นว่า a = 2 มีมากกว่า 1 ครั้งพอรอบต่อๆ มายิ่งมีจำนวนมากขึ้นเรื่อยๆ ขนาดเกินเงื่อนไขให้หยุดทำงาน ( a > 10 ให้เรียก เรียกใช้ clearInterval ) ก็ยังไม่หยุด แก้ได้โดยเพิ่มเงื่อนไขในการเรียกตัวเองตามตัวอย่าง
[sourcecode language=”html”]
<!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>
[/sourcecode]
About the author