JavaScript SetTimeout: Unlocking the Secrets of Time Control

javascript settimeoutfunctionYou can’t stop the flow of time, but you can control timing operations on a computer using methods such as setTimeout. Master this one and you can do everything from creating animations to refreshing your web pages with new data periodically. Suppose you wanted to display an alert that displayed “Hello”. The following example does that.

alert(‘Hello’);

If you’d like that alert statement to execute about 2 seconds after a browser runs that code, pass the code as the first parameter to setTimeout, as shown below:

setTimeout("alert(1)", 2000);

The first parameter in this setTimeout is a quote-delimited string that contains a call to the alert function. The second parameter is a delay value that tells browsers when to execute the code in the first argument. Because the delay value is in milliseconds, setTimeout executes the alert statement 2 seconds after the browser runs the setTimeout statement. Use this syntax any time you need to make code execute one time at an interval you specify.

New to JavaScript arguments? Learn more at Udemy.com.

Master the Basic Functionality

This example delays the execution of an alert command that displays “Hello.” A more useful task might be to make an image appear a few seconds after someone visits your web page. Although you could write the code to make an image disappear, it would probably take more than a few statements to do that. Instead of passing a string that contains code to setTimeout, you can pass setTimeout the name of a function that contains the code you want to run, as seen in the following example:

setTimeout("sayHello()", 2000);

This setTimeout calls the sayHello function 2000 milliseconds after a browser executes the setTimeout statement. Here is the sayHello function:

function sayHello() {

alert("Hello!");

}

When your JavaScript code runs, the setTimeout statement, a browser displays “Hello” two seconds later. Note that “sayHello()” is in quotes in the setTimeout statement. JavaScript  assumes that you want it to run what’s between the quotes when it sees “sayHello()” within quotes.

Instead of passing the name of a function in quotes to setTimeout, you can pass a function pointer, as shown below:

setTimeout(sayHello, 2000);

When you pass this function pointer to setTimeout, do not include it in quotes or put parenthesis after the pointer’s name.

Explore Advanced Functionality

Finally, you can pass an anonymous function to setTimeout, as shown in the following example:

setTimeout(function() {

setColor(“red”);

}, 3000)

}

This anonymous function calls a function named setColor.  The anonymous function also passes “red” to the setColor function. The delay factor is 3000. If your setColor function accepted an argument, its value would be “red” in this instance. The function could use that value as needed to perform its task.

As the example shows, anonymous functions give you the ability to pass arguments to another function; you can’t do that by passing a pointer to a function to setTimeout.

In examples so far, the setTimeout method makes code run one time after a specified delay. When you’d like your code to run continuously, create a function that calls itself recursively, such as the one shown below:

function updateTime() {

var clock = document.getElementById('clockDiv');

var currentTime = new Date();

clock.innerHTML = currentTime.toLocaleTimeString();;

setTimeout('updateTime()', 2000);

}

The first statement assumes that your web page has a div with an ID of “clockDiv.” When that statement runs, it stores a reference to the clockDiv div in the clock variable.

Learn more about using JavaScript functions productively at Udemy.com.

The next two statements get the current time and set the clock div’s innerHTML to that time. Finally, the setTimeout statement calls the updateTime function. Because the delay value is 1000, the updateTime method runs 1 second later. When this code executes in a browser, you’ll see a div with time values that change every one second. This code runs perpetually because there’s no mechanism in this example to stop it.

Set Interval: An Alternative Timing Method

JavaScript has another timer method named setInterval that’s similar to setTimeout. SetInterval runs the code you specify repeatedly, as shown below:

setInterval(sayHello, 2000);

When this statement runs, it tells a browser to execute the sayHello function every 2000 milliseconds. You might prefer to use setInterval when you need to run code repeatedly using a single statement. One important factor to consider is the way browsers execute setTimeout and setInterval. If you tell setInterval to call a function every 2000 milliseconds, the browser runs the function every 2000 milliseconds.

On the other hand, setTimeout doesn’t execute code again until that code finishes running. If you tell setTimeout to run a function named performComplexTasks every 2000 milliseconds and that function takes 3000 milliseconds to run, setTimeout won’t call the function again for 5000 milliseconds. Remembering this fact can help you understand why your setTimeout code might not run as expected sometimes.

Additional Timer Tips

You may find it helpful to create a variable that holds a reference to a setTimeout or setInterval method. The following examples demonstrate how to save these types of references:

var myTimer1 = setTimeout(function1, 8000);

var myTimer2 = setinterval(function2, 2000);

After these statements run, the myTimer1 variable holds a reference to a setTimeout object and the myTimer2 variable holds a reference to the setInterval object. Since this setInterval method call executes the function2 function every 2000 milliseconds, function2 runs every 2000 milliseconds. You can stop it anytime by calling the clearInterval function, as shown below:

ClearInterval(myTimer2)

The setTimeout statement tells a browser to run function1 after 8000 milliseconds elapses. You can prevent that function from executing by calling clearTimeout(myTimer1) before the 8000 milliseconds elapses.

Site developers use setTimeout a variety of creative ways. If you’d like to create a slideshow, write a setTimeout statement that calls a page update function repeatedly. That function could change an image’s src property to point to another image URL.  Control the length of time between successive slides by adjusting setTimeout’s delay factor.

SetTimeout can also help you animate Web page objects. For instance, if you’d like to move an object across the page, create a function that change’s the object’s top and left property values every time the function runs. Use setTimeout to call that function recursively, as discussed previously. Make a button inactive after 10 minutes by using setTimeout to call a function that disables the button after 10 minutes. This might be useful on a Web page that gives people a limited time to perform a specific task.  You’ll probably brainstorm other useful tasks setTimeout can perform after you experiment with this useful method.

Pick up rock star JavaScript tips at Udemy.