0

I'm trying to create a prompt that has a time delay, the value that is written in the prompt is then used in other areas of the form. I have written some javascript coding but I believe there is a minor thing that i am doing wrong as currently the prompt and delay are working, but because the setTimeout function is being used, that is what is being displayed in the form, instead of the content of the prompt. This is my Javascript?

var name = setTimeout(function(){ prompt("What is your name?", "Type your full name here")},750); 
document.write("Document Written By: " + name + " (" + day + "/" + month + "/" + year + ") ")
Kev
  • 112,868
  • 50
  • 288
  • 373
  • 4
    What do you mean "prompt with time delay"? And for all that's holy, please stop using `document.write`. – Jon Feb 11 '13 at 23:02
  • A prompt box that appears on page load, I want it to have about a 1 second delay before appearing –  Feb 11 '13 at 23:03
  • 1
    Perhaps your question is not titled very well, since *the delay is working*. Matt's answer should cover the rest. – Jon Feb 11 '13 at 23:04
  • What is the issue of using document.write, can you reccommend alternatives –  Feb 11 '13 at 23:08

1 Answers1

3

If it depends on the value, and a function is asynchronous, you've got do it in the callback. Just like every other asynchronous piece of JavaScript...

setTimeout(function(){
    name = prompt("What is your name?", "Type your full name here");
    document.write("Document Written By: " + name + " (" + day + "/" + month + "/" + year + ") ");
},750);

But as @Jon commented, please do not use document.write.

Community
  • 1
  • 1
Matt Ball
  • 332,322
  • 92
  • 617
  • 683
  • Something still isnt quite right, by using this coding It takes what is written in the prompt box and displays it in a new tab, I wanted the contents of the prompt box to be written within the original body tags –  Feb 11 '13 at 23:07
  • Yup, don't use `document.write`. – Matt Ball Feb 11 '13 at 23:08
  • can you recommend an alternative –  Feb 11 '13 at 23:09
  • Proper DOM manipulation APIs. Are you using jQuery or any other cross-browser library? – Matt Ball Feb 11 '13 at 23:09
  • Nope, just straight JavaScript and HTML –  Feb 11 '13 at 23:10
  • Then straight DOM. Try https://developer.mozilla.org/en-US/docs/DOM/Document.createTextNode and https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild – Matt Ball Feb 11 '13 at 23:12