Help the beginner!

Question: If we write the delay code of the alert as:

setTimeout("T1()", 500); function T1() { alert() } 

when loading alert pops up.
If you issue this action as a function FF () - the program does not work.

What's the matter?

The whole script is as follows.

 <script> function FF() { setTimeout("T1()",500); function T1() { alert() } } </script> </head> <body> <body bgcolor="00ff00"> </body> </html> 
  • you have incorrect markup: several body elements, and the FF function is not called anywhere, so the alert does not appear. And a plus: when a string is passed, its contents are executed in a global context, and since T1 is a local function by timeout, there will be an error since this function will not be found - Grundy

2 answers 2

In order for the function to work, it needs to be called, for example, like this:

 <script> function FF() { setTimeout(T1,500); function T1() { alert() } } FF(); </script> </head> <body> <body bgcolor="00ff00"> </body> </html> 

Or there are self-invoking functions, they have no name, but they are called right away. If you take your example as a basis, it would look like this:

 (function () { setTimeout(T1,500); function T1() { alert() } }()); 
  • and if you tried, you would see that it gives an error: ReferenceError: T1 is not defined - Grundy
  • @Grundy instead of poking, it would be possible to fix it simply, now everything works correctly - Yaroslav Molchan
  • one
    Instead of rushing to write an answer, you could check what you advise - Grundy
  • but for now you check, you can change your mind at all :) - Igor
  • @Igor replied the answer even an hour ago, it works, you can check :) - Yaroslav Molchan

Just wrap your alert into a function and everything will work.

 function alertWithDelay() { setTimeout(function() { alert('alert-text') }, 5000); } alertWithDelay(); 

  • In question alert already wrapped in function T1 - Grundy
  • @Grundy I see what the author wrote, but is the name of the function written in quotes?) With the anonymous function will not be mistaken - nueq
  • string is a valid parameter for setTimeout. - Grundy
  • @Grundy, valid, then valid, but readability is lost for me personally, the function name is the name of the function and does not require quotes, the string is a string. - nueq