无法在Javascript中进行递归调用 [英] Unable to make recursive call in Javascript

查看:64
本文介绍了无法在Javascript中进行递归调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行此程序时,我在Firefox中收到错误消息:

When I try to run this program, I get an error in Firefox saying that:


第41行未定义moveDate

moveDate is undefined on line 41

(指行 window.setTimeout(moveDate(),100);

任何想法为什么?我认为递归函数能够定义自己然后调用自己。

Any ideas why? I thought recursive functions were able to define themselves and then call upon themselves.

function monthScroller(){
    document.getElementById("month").style.visibility = "visible";
    var x = 0;
    var y = 0;
    var dest_x = window.innerWidth/2;
    var dest_y = window.innerHeight/2;  
    var interval = 1;

    function moveDate() {
        if(x<dest_x){ x = x + interval;} 
        if(y<dest_y){ y = y + interval;}

        document.getElementById("month").style.top  = y+"px";
        document.getElementById("month").style.left = x+"px";

        if ((x+interval < dest_x) && (y+interval < dest_y)) {
                window.setTimeout("moveDate()",100);
        }
        else{
            name();
        }
    }
    moveDate();
}


推荐答案

是的,它们是。然而, window.setTimeout(moveDate(),100); 将评估全局范围内的代码字符串 - 没有 moveDate 在那里找到。相反,将函数引用传递给 setTimout()

Yes, they are. Yet, window.setTimeout("moveDate()",100); will eval that code string in the global scope - no moveDate to be found there. Instead, pass the function reference to setTimout():

 window.setTimeout(moveDate, 100);

这篇关于无法在Javascript中进行递归调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆