i came upon this code while studying settimeout. the settimeout executes an alert 5 seconds after a button is clicked.
<input type="button" name="clickMe" value="Click me and wait!"
onclick="setTimeout('alert(\'Surprise!\')', 1000)">
however, i saw that the alert string inside has a format ive never seen before. the \ occurs before the ‘ Surprise! \’. what is its use?
This is the indented command:
alert('Surprise!'). It contains two quotes.In this case the command is passed as a string to
setTimeout.This string is delimited by quotes:
'string'.Together this would look like
'alert('Surprise!')', which is invalid syntax, because it’s parsed like this:So the quotes inside the string are escaped to signify “this is not the end of the string”.
This is about the worst possible way to do this though. A better way would be to alternate the two available quote types:
This will mess up in this case though because it will confuse the HTML parser.
An even better way is to pass an anonymous function instead of a string:
An even betterer way is unobtrusive Javascript, in which you’re not using HTML
onclickattributes, but attach the Javascript to a DOM element programmatically: