Jump to content

Why Does Javascript Do It The Wrong Way Around?


Recommended Posts

I have a question about a little part of a script I am making. The poroblem is that Javascript does the script the in the wrong way, and I don't understand why (and how to solve it). The script has to do this: print starttime, wait three seconds, then print endtime. But what it does is this: wait three seconds, then print starttime and endtime. Thats the wrong way around! How can I make Javascript to write the starttime BEFORE thew loop?????? Thx. --- <html><head><title>test</title></head><body><script type="text/javascript" language="javascript">var run = true;var starttime=new Date().getTime();document.writeln(starttime+"<br />");// why doesn't it do above command, until AFTER below commandwhile (run) { nowtime = new Date().getTime(); if ((nowtime-starttime)>3000) { run = false; document.writeln(nowtime); }; }</script></body></html>

  • Like 1
Link to post
Share on other sites

Because you're making the browser freeze with a loop. The browser tries to finish scripts before printing anything to save rendering time. You should use setTimeout or setInterval for timed events.

document.writeln(starttime + "<br/>");setTimeout(3000, function() {  document.body.innerHTML += (new Date()).getTime();});

I can't use document.write after the page has loaded because it will clear the whole screen before writing so I'm writing with a better method.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...