开发者

Recursion function not defined error

Hi i have a problem with recursion.

i followed this example from wc3 http://www.w3schools.com/jsref/met_win_settimeout.asp But mine seems to not work at all.

function rotateImages(start)
  {
  var a = new Array("image1.jpg","image2.jpg","image3.jpg", "image4.jpg");
  var c = new Array("url1", "url2", "url3", 开发者_Python百科"url4");
  var b = document.getElementById('rotating1');
  var d = document.getElementById('imageurl');
  if(start>=a.length)
      start=0;
  b.src = a[start];
  d.href = c[start];
  window.setTimeout("rotateImages(" + (start+1) + ")",3000);
  }

  rotateImages(0);

Firebug throws the error :

rotateImages is not defined
[Break On This Error] window.setTimeout('rotateImages('+(start+1)+')',3000);

However if i change the timeOut to :

window.setTimeout(rotateImages(start+1),3000);

It recursives but somehow the delay doesn't work and gives me too much recursion(7000 in a sec)


There are many reasons why eval should be avoided, that it breaks scope is one of them. Passing a string to setTimeout causes it to be evaled when the timer runs out.

You should pass a function instead.

window.setTimeout(rotateImages(start+1),3000);

This calls rotateImages immediately, then passes its return value to setTimeout. This doesn't help since rotateImages doesn't return a function.

You probably want:

window.setTimeout(rotateImages,3000,[start+1]);

Or create an anonymous function that wraps a closure around start and pass that instead:

window.setTimeout(function () { rotateImages(start + 1); },3000);

The latter option has better support among browsers.


Be wary of code from W3Schools.

The other answers give a solution. I'll just add that you're recreating the Arrays and repeating the DOM selection every time the rotateImages function is called. This is unnecessary.

You can change your code like this:

(function() {
    var a = ["image1.jpg","image2.jpg","image3.jpg", "image4.jpg"];
    var c = ["url1", "url2", "url3", "url4"];
    var b = document.getElementById('rotating1');
    var d = document.getElementById('imageurl');

    function rotateImages(start) {
      b.src = a[start];
      d.href = c[start];
      window.setTimeout(function() {
          rotateImages( ++start % a.length );
      }, 3000);
    }

    rotateImages(0);
})();


Try this syntax:

window.setTimeout(function() {
    rotateImages(start+1);
},3000);

setTimeout() expects a function reference as the 1st parameter. Simply putting a function call there would give the return value of te function as the parameter, this is why the delay did not work. However your first try with evaluating a string was a good approach, but it is not recommended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜