Javascript setTimeout 忽略时间参数
这不是我第一次使用 setTimeout(),但我无法弄清楚问题出在哪里。 setTimeout() 的代码部分正确执行,但它立即执行,没有延迟。如果有人能看到这个问题,那就会有帮助。这是代码:
if(token==1){
img1.src=ssImages[imgNum];
num1=0;
num2=10;
setTimeout('crossFade()',2500);
}
It's not the first time I've used setTimeout(), but I can't figure out what the problem is. The code part of the setTimeout() is executing correctly, but it is executing immediately without the delay. If anyone can see the problem, that would help. Here's the code:
if(token==1){
img1.src=ssImages[imgNum];
num1=0;
num2=10;
setTimeout('crossFade()',2500);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你确定这是代码吗?如果它立即执行,通常有两个原因:
setTimeout(foo(), 1234)
);但这些原因都不适用于您的代码,因此请检查其余代码是否有对该函数的任何其他调用。
无论如何,您确实应该传递一个函数而不是字符串:
或者,如果您需要指定任何参数:
Are you sure this is the code? If it executes immediately there are usually two reasons:
setTimeout(foo(), 1234)
);But none of the reasons apply to your code so check the rest of the code if there are any other calls to that function.
Anyway, you should really pass a function instead of a string:
Or, if you need to specify any arguments:
我同意《盗贼大师》的观点。窗户。 setTimeout 方法有两个参数:
1) 函数 OR 表达式
2) 时间(以毫秒为单位)
在代码中,您提供一个字符串或一个表达式:
setTimeout('crossFade()',....)
与使用 eval 一样,通常不鼓励这样做。您应该传递一个函数 - 要么命名为:
setTimeout(crossFade,....)
要么按照建议的匿名方式:
setTimeout(function(){crossFade()},....
这就是您可以解决此代码问题的所有方法除非您提供一个示例 jsfiddle 以便我们查看调用的上下文。
I agree with Theifmaster. The window. setTimeout method takes two arguments:
1) Function OR Expression
2) Time in ms
In your code you provide a string or an Expression :
setTimeout('crossFade()',....)
This is generally discouraged as with the use of eval. You should pass a function - either named:
setTimeout(crossFade,....)
OR as suggested anonymous:
setTimeout(function(){crossFade()},....
This is about all you can do to trouble shoot this code unless you provide an example ok jsfiddle for us to see the context this is called.