我正在尝试使用setTimeout编写一个简单的代码,并且setTimeout不会等待它所设想的时间并且代码立即执行.我究竟做错了什么?
setTimeout(testfunction(), 2000);
Run Code Online (Sandbox Code Playgroud) 简单的说...
为什么
setTimeout('playNote('+currentaudio.id+', '+noteTime+')', delay);
Run Code Online (Sandbox Code Playgroud)
完美地工作,在指定的延迟后调用函数,但是
setTimeout(playNote(currentaudio.id,noteTime), delay);
Run Code Online (Sandbox Code Playgroud)
同时调用函数playNote?
(这些setTimeout()s在for循环中)
或者,如果我的解释太难阅读,这两个函数之间有什么区别?
这是我第一次真正深入了解JavaScript.当然我以前用过它,但我从来没有真正从头开始写任何东西.
无论如何,我有一个非常奇怪的问题,我希望有人可以为我找到.
我正在尝试将文本从div淡出从黑色变为白色.很简单,是吗?
以下代码有效.它会将颜色更改为白色,但是会忽略500ms的setTimeout时间.
如果您使用Chrome并查看JS控制台,您将很容易看到几乎是瞬间调用doFade()方法,而不是每500毫秒.
有谁能解释一下?
var started = false;
var newColor;
var div;
var hex = 0;
function fadestart(){
if (typeof fadestart.storedColor == 'undefined') {
div = document.getElementById('test');
fadestart.storedColor = div.style.color;
}
if(!started){
console.log('fadestart');
newColor = fadestart.storedColor;
started = true;
setTimeout(doFade(), 500);
}
}
function fadestop(){
console.log('fadestop');
div.style.color = fadestart.storedColor;
started = false;
hex = 0;
}
function doFade(){
if(hex<=238){
console.log(hex);
hex+=17;
div.style.color="rgb("+hex+","+hex+","+hex+")";
setTimeout(doFade(), 500);
}
}
Run Code Online (Sandbox Code Playgroud) 这是我的问题.我有这个功能来测试代理服务器.
function crawl() {
var oldstatus = document.getElementById('status').innerHTML;
document.getElementById('status').innerHTML = oldstatus + "Crawler Started...<br />";
var url = document.getElementById('url').value;
var proxys = document.getElementById('proxys').value.replace(/\n/g,',');
var proxys = proxys.split(",");
for (proxy in proxys) {
var proxytimeout = proxy*10000;
setTimeout(doRequest(url,proxys[proxy]), proxytimeout);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望以大约10秒的间隔调用'doRequest()'函数,但即使使用setTimeout(),也会立即调用函数.
欢迎任何想法,谢谢.
PS:即使我为'proxytimout'设置了一个任意值,它也没有效果.
通过使用setTimeout方法调用函数而不是直接调用函数,可以在javascript中避免堆栈溢出吗?我对setTimeout的理解是它应该启动一个新的callstack.当我查看chrome和IE的callstack时,似乎setTimeout调用正在等待函数调用返回.
这只是调试器的属性还是我的理解有缺陷?
编辑
虽然下面提供的答案是正确的,但我遇到的实际问题与我调用setTimeout(aFunction(),10)的事实有关,因为括号因此立即评估aFunction.这个问题把我排除在外.
我刚刚进入Java.我正在编写一个简单的脚本来打开一个窗口,然后在短暂的延迟后关闭它.我尝试了以下各种内涵,但无济于事.该功能有效(因为它打开,然后关闭窗口),但延迟不会发生.
function manualWindow(){
testWindow = window.open("popup.php","interaction","resizable=0,width=800,height=600,status=0");
setTimeout(testWindow.close(),5000);
}
Run Code Online (Sandbox Code Playgroud)
谢谢