我正在尝试使用setTimeout编写一个简单的代码,并且setTimeout不会等待它所设想的时间并且代码立即执行.我究竟做错了什么?
setTimeout(testfunction(), 2000);
Run Code Online (Sandbox Code Playgroud) 这是我第一次真正深入了解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) 有人可以帮助我理解为什么这段代码:
for (var i =0; i < 2; i++) {
setTimeout(console.log(i), 0);
}
console.log("aaa");Run Code Online (Sandbox Code Playgroud)
将会写:
0
1
aaa
Run Code Online (Sandbox Code Playgroud)
但该代码:
会这样写:
aaa
2
2
Run Code Online (Sandbox Code Playgroud)
请注意,我理解第二节是如何进行的。工作,我不明白为什么第一个会有所不同。
谢谢!
tablePush单击某个项目时,该函数会将id推送到表中.
但是,它没有点击运行,我不明白为什么.
这是我的代码:
function tablePush() {
console.log('OK');
if (pickPicture) {
console.log('TRUE');
} else {
console.log('on rentre dans le else');
console.log(this);
var idPic = this.getAttribute('id');
console.log(idPic);
table.push(idPic);
pickPicture = true;
}
}
var picture = document.getElementsByClassName('picture'),
table = [],
pickPicture = false;
for (var i = 0; i < picture.length; i++){
picture[i].addEventListener('click', tablePush());
}
Run Code Online (Sandbox Code Playgroud)