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?

Answers:

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.