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">

<meta charset="utf-8">
<title>Set TimeOuts</title> 
<script type="text/javascript" src="">
<script language="javascript">
function setBGColor()
var div1 = document.getElementById("div1");
function setColor(color)
<div id="div1" onclick="setBGColor()";>THIS IS THE COLOR TEST</div> 

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?



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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.