Bella Huang Bella Huang - 2 months ago 9
jQuery Question

setTimeout() function isn't working

I want the animation works continuously, but there will always be an error in console: "VM1179:1 Uncaught ReferenceError: move is not defined". Don't know why... Copy the code below

$(document).ready(function(){

function move(){
$("#block").animate({left:"+=50px" },1000).animate({top:"+=50px"},1000).animate({left:"-=20px"},1000).animate({top:"-=20px"});
setTimeout('move()',1000);
}
move()
})

Answer

When you use a string as argument, such as

setTimeout('move()',1000);

setTimeout picks the function from the global scope (window, in your case), but since you are defining move() inside the document.ready argument function, it is not going to the global scope.

The solution is to directly use a reference to the move function as argument to the setTimeout:

setTimeout(move, 1000);

This way it picks it from the local scope, where the function exists.