JavaScript setTimeOut似乎不像我期望的那样工作 [英] JavaScript setTimeOut doesn't seem to work like I expect

查看:108
本文介绍了JavaScript setTimeOut似乎不像我期望的那样工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的JavaScript文件,我在Chrome(localhost ...)下运行。会发生的是,不是将DIV背景颜色设置为绿色然后再设置为红色,而是将其设置为红色。第一个setTimeout似乎被忽略。

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>

但是,如果我在setColor函数中添加警报(颜色),我可以看到div bgcolor先变黄。此外,6000也被忽略。为什么?

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?

推荐答案


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


正在呼叫 setColor('yellow')并将返回值 undefined )传递给 setTimeout

你需要传递一个函数。

同样重要的是要注意 setTimeout 将导致一段时间后调用一个函数。它在这段时间内不会让JavaScript睡眠。

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); 

...将在0时调用 setTimeout ,然后稍后再调用 setTimeout ,然后在6s和<$ c时调用 setColor('yellow') $ c> setColor('red')之后不到一秒钟。

… 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.

这篇关于JavaScript setTimeOut似乎不像我期望的那样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆