我正在尝试使用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) 当调试器在d中触发时,下面的代码有一个新的callstack(这里是 jsfiddle )
function c() {
setTimeout( d, 1000 );
}
function d() {
debugger;
}
c();
Run Code Online (Sandbox Code Playgroud)
如果我们修改使用setTimeout( d(), 1000 );哪个代码括号(括号:)
function c() {
setTimeout( d(), 1000 );
}
function d() {
debugger;
}
c();
Run Code Online (Sandbox Code Playgroud)
那么callstack有c()和d()(这里是 jsfiddle ).为什么?