views:

69

answers:

4

problem with setTimeout "function is not define" !

What is the problem in this code ?

$(document).ready(function(){ 

 function ISS_NextImage() { //ImageSlideShow NextImage
  $('.ImageSlideShow').each(function() {
   alert($(".correntImage", this).text());
  });
 }

 var t=setTimeout("ISS_NextImage();",1000);

});
+4  A: 

When you eval code, it is done in the global scope. Since the function you are trying to call is locally scoped, this fails.

Pass the function to setTimeout instead of passing a string to be evaled.

var t=setTimeout(ISS_NextImage,1000);
David Dorward
*"When you eval code, it is done in the global scope"* **Sort of** (And therein lies one of the problems.) The scope in which `setTimeout` happens is *different* from the scope in which `eval` happens. Which doesn't change the wisdom of your basic recommendation of not using strings, but function references.
T.J. Crowder
A: 

Avoid passing a string to setTimeout(). Just pass a reference to the function instead:

var t = setTimeout(IIS_NextImage, 1000);
istruble
A: 

you could also:

$(function() { 
    var t = setTimeout(new function() {
       $('.ImageSlideShow').each(function() {
           alert($(".correntImage", this).text());
       });
    }, 1000);
});
Ryan Ternier
You could, but it would make it harder to read, and the choice of using the `new` keyword is … odd.
David Dorward
A: 

Try changing your set timeout call to this:

var t=setTimeout(function(){ISS_NextImage();},1000);
mcgregok
...which is what istruble and others already said, several minutes ago.
T.J. Crowder
A function that does nothing except call a different function with no arguments is usually a bad idea.
David Dorward
@David - But if you did want to include arguments with `ISS_NextImage()`, this would be the way to go..... and that'd be pretty common with a next image function since you might want to do something like `var t=setTimeout(function(){ISS_NextImage((imageIndex + 1) % numImages);},1000);`
Peter Ajtai
generally I use this format for a few reasons. 1) To help break habits of developers that pass strings that are evaled to settimeout and 2) to be able to get closure and easily work around the problem of 'this' being the global object window by doing something like this:var self=this;setTimeout(function(){ISS_NextImage(self);},1000);In my experience new developers don't understand scope in javascript and that passing the name of the function that you are actually sending in window.function (most of the time) which is why I have found it better to use this syntax around new developers.
mcgregok