«

Apr 14

How to use JavaScript setTimeout

The setTimeout function allows you to delay the execution of code.  The setTimeout function works by specifying a string of code followed by the delay in milliseconds.  For example:

setTimeout(“alert(‘timeout!’)”, 1000)

The code above will display an alert box that says “timeout!” after 1 second (1000 milliseconds).  Because setTimeout uses strings of text that it tries to execute later, things don’t always work as expected.  Consider the following example:

var test = function() { var obj1 = new Object(); obj1["key"] = “value”; setTimeout(‘alert(obj1["key"])’, 1000); }

The code above defines a function called test.  The function creates a new object, sets the attribute “key” to “value”, and calls setTimeout to display an alert with the value of key 1 second later.  However, calling this function will result in a run-time error because obj1 is outside the scope when the alert function is executed.  To fix this, the code must be written differently:

var test = function() { var obj1 = new Object(); obj1["key"] = “value”; setTimeout(“alert(\”"+obj1["key"]+”\”)”, 1000); }

This code works as expected because the value of key is included directly in the string.  The code does not attempt to reference obj1 later.  But, let’s say you want to pass an entire object to some function.  Simply convert the object to JSON.  For example:

var test = function() { var obj1 = new Object(); obj1["key"] = “value”; setTimeout(“some_function(“+JSON.stringify(obj1)+”)”, 1000); }

 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>