Timeout rocks!

We can execute a JavaScript function after a specified delay using setTimeout(). If we want to run a function many times say, any 15 seconds, we can use setInterval().

Here we'll see how to use setTimeout() - setInterval() is quite the same, just remember that to stop it calling the associated function we could call clearInterval() - in an example that is meant to be an extension of the already seen basic JavaScript example.

The point of the code is that when we click on the picture, it is changed with a second one, but the new one shift automatically back to the default after a while (specified in millisecs):

<html>
<head>
<title>A whimsical page</title>

<script type="text/javascript">
var userName;

function greet() {
alert("Hello from a whimsical page!");
}

function setHappy(happy) {
var element = document.getElementById('rock');

if(happy) {
element.src = "image2.png";
element.alt = "Happy";
}
else {
element.src = "image1.png";
element.alt = "Bored";
}
}

function touchMe() {
if (userName) {
alert("I like the attention, " + userName + ". Thank you.");
}
else {
userName = prompt("What is your name?", "Enter your name here.");
if (userName)
alert("Nice meeting you, " + userName + ".");
}

setHappy(true);

setTimeout("setHappy(false)", 3000);
}
</script>
</head>

<body onload="greet()">
<div style="margin-top:100px; text-align:center">
<img id="rock" src="image1.png" alt="Bored" style="cursor:pointer" onclick="touchMe()" />
</div>
</body>
</html>


Post based on an example found in chapter three of Head First JavaScript, you should read it too, if you want more details, and some fun, too.

No comments:

Post a Comment