Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

JavaScript setTimeOut doesn't seem to work like I expect

This is a simple JavaScript file which I run under 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. The first setTimeout seems to be ignored.

<!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. Also, the 6000 is ignored as well. WHY?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
setTimeout(setColor('yellow'),6000);

You are calling setColor('yellow') and passing the return value (which is undefined) to 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. It doesn't make JavaScript sleep for that period.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...