1
 var k=0;var n=0;
  function shiftrigh(){
  n=n+1;
  if(n<=193)
   window.setTimeout(shiftright(),100);
  else
      n=0;}

function shiftright(){
   k-=1;
   document.getElementById("abcmngcontainer").style.left=k+"px";
   window.setTimeout(shiftrigh(),100);
}

function shiftlef(){
  n=n+1;
  if(n<=193)
   window.setTimeout(shiftleft(),100);
  else
      n=0;}

function shiftleft(){
   k+=1;
   document.getElementById("abcmngcontainer").style.left=k+"px";
   window.setTimeout(shiftlef(),100);
}

Hi, I have the above code. The function shiftrigh when called invokes shiftright and then a cycle is created then goes on until n is 193. Same is the case for the shiflef pair. The code is working but it is working pretty quick. Whether I decrease the time value in settimeout or increase it, it remains the same. The updates are pretty quick, not smooth enough to see.

4

3 回答 3

7

Change:

window.setTimeout(shiftright(),100);

to:

window.setTimeout(shiftright,100);

Note the missing parens. The same with shiftleft() -> shiftleft.

This is a common misunderstanding in JavaScript. setTimeout() requires a reference to a function (shiftright). What you are doing is calling that function immediately and passing whatever was returned from it to setTimeout(). Clearly not what was intended.

于 2012-08-26T12:28:48.933 回答
0

You are using window.setTimeout wrong!

window.setTimeout(shiftlef(),100);

You have to pass a function reference, not the return code of the function. So the right version looks like this:

window.setTimeout(shiftlef,100);
于 2012-08-26T12:29:17.887 回答
0

setTimeout will need a function-NAME or a function-"variable"/"pointer" as first argument...

in your code, you pass the RETURN value of your function-call as first parameter to "setTimeout"....

just remove the braces ->

window.setTimeout(shiftleft, 100)

于 2012-08-26T12:29:22.473 回答