<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script> function errorTimeOut(strInTest) { alert('I will wait 10 seconds, but no variables (error: Uncaught ReferenceError: strTest is not defined). ' + strInTest) } function errorAlert() { var strTest = "I am here!"; setTimeout("errorTimeOut(strTest)", 10000); } function correctTimeOut(strInTest) { alert('I was waiting 20 seconds, and everything is ok: ' + strInTest) } function correctAlert() { var strTest = "I am here!"; setTimeout(function() { correctTimeOut(strTest) }, 20000); } setTimeout(alert('I am fired immediately'), 10000); errorAlert(); correctAlert(); </script> </head> <body> </body> </html>
As you can see from previous code, setTimeout(alert('I am fired immediately'), 10000); will not work.
setTimeout("alert('I will wait')", 10000); - this will work, alert under quotes, but you can not pass varibles.
And the code:
function correctAlert() { var strTest = "I am here!"; setTimeout(function() { correctTimeOut(strTest) }, 20000); }
Will work properly.