Javascript timeout usage

Home - Tutorials - Date and time

In this tutorial I will show you how to use timeouts in your JavaScript code. With this information you will be able to create a usefull timer.

Tutorial info:

Name:Javascript timeout usage
Total steps:3
Category:Date and time
Product:See complete product

Bookmark Javascript timeout usage

AddThis Social Bookmark Button

Step 1 - Using timeouts in JavaScript

Javascript timeout usage


Now and again it can happen that you want to time some task on your web page. For example you want to display the current time value on your site. In this case you need to update your page in every seconds. Don't worry! This task is quite simple using JavaScript. 

Before creating a complete clock we need to learn the basics of this topic. First of all there is a JavaScript function timeout() which will be used.

The timeout syntax is:  

var t = setTimeout("javascript statement",milliseconds);

Well, the first parameter is a standalone JavaScript command or it can be a function. This will be executed when the time in the second parameter was elapsed. As you can see you need to use milliseconds.

The return value is an identifier for this timer event. So if you want to cancel it you need to use this identifier.

A very simple example is the code below. Here we will display a simple alert message. We use 2 buttons here. The click on the first one will display an alert without timeout, however the click on the second button displays a message using a 3 seconds timeout.

  1. <body>
  2. <script language="javascript" type="text/javascript">
  3. <!--
  4. function delayedAlert(){
  5. setTimeout("alert('This alert was delayed');",3000);
  6. }
  8. function normalAlert(){
  9. alert('No timeout');
  10. }
  11. //-->
  12. </script>
  14. <button onclick="normalAlert();">No timeout</button>
  15. <button onclick="delayedAlert();">Delayed alert</button>
  16. </body>

As you can see here we didn't used the return value of the timeout function. It is because in this case we only want to make a certain task only once. In case of displaying current time we need to use a recursive call.

Next Step of Javascript timeout usage

Tags: javascript timeout, timeout script, javascript, timeout

Javascript timeout usage - Table of contents
Step 1 - Using timeouts in JavaScript
Step 2 - Displaying the current time
Step 3 - Complete timeout demo code

GAD Tower

F1 Site Family
Database F1
Java F1
JavaScript F1

Family tutorials
PHP Array
PHP Redirect
PHP Session
AJAX File Upload
AJAX Rating System
MySQL Create User
Mysqldump Example
MySQL Concat

Total time: 0.1542