简体   繁体   English

JavaScript setTimeOut 似乎不像我预期的那样工作

[英]JavaScript setTimeOut doesn't seem to work like I expect

This is a simple JavaScript file which I run under Chrome (localhost...).这是一个简单的 JavaScript 文件,我在 Chrome (localhost...) 下运行。 What happens is that instead of the DIV background color set to Green and then to Red, it is just set to Red.发生的情况是,DIV 背景颜色没有设置为绿色,然后设置为红色,而是设置为红色。 The first setTimeout seems to be ignored.第一个 setTimeout 似乎被忽略了。

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8">
<title>Set TimeOuts</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script> 
<script language="javascript">
function setBGColor()
{ 
var div1 = document.getElementById("div1");
setTimeout(setColor('yellow'),6000);
setTimeout(setColor('red'),6000); 
} 
function setColor(color)
{
    div1.style.backgroundColor=color; 
}
</script>
</head>
<body>
<div id="div1" onclick="setBGColor()";>THIS IS THE COLOR TEST</div> 
</body>
</html>

BUT, if I put an alert(color) in the setColor function, I can see the div bgcolor go yellow first.但是,如果我在 setColor function 中添加警报(颜色),我可以首先看到 div bgcolor go 黄色。 Also, the 6000 is ignored as well.此外,6000 也被忽略。 WHY?为什么?

setTimeout(setColor('yellow'),6000);

You are calling setColor('yellow') and passing the return value (which is undefined ) to setTimeout .您正在调用setColor('yellow')并将返回值undefined )传递给setTimeout

You need to pass it a function.你需要给它传递一个函数。


It is also important to note that setTimeout will cause a function to be called after a time.同样重要的是要注意setTimeout将导致函数在一段时间后被调用。 It doesn't make JavaScript sleep for that period.它不会让 JavaScript 在这段时间内休眠。

setTimeout(setColor.bind(window, 'yellow'),6000);
setTimeout(setColor.bind(window, 'red'),6000); 

… will call setTimeout at 0s, then call setTimeout again a fraction of a second later, then call setColor('yellow') at 6s and setColor('red') a fraction of a second after that. ...将调用setTimeout在0,然后调用setTimeout再晚一秒的一小部分,然后调用setColor('yellow')在6S和setColor('red')之后第二个的一小部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM