Unable to make recursive call in Javascript

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

moveDate is undefined on line 41

(referring to the line 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)) {



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);

"moveDate" is scoped inside of the monthScroller method. Anything outside of the brackets of the monthScroller function can't see the "moveDate" function. So... when the setTimeout runs, the scope "window" and window doesn't have a function named "moveDate" in scope. What you need to do is change the call to the following:


That should work for you. That way you are passing the moveDate function/object into the setTimeout.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.