0

I have 3 functions that being called like this:

<body onLoad="startIt(),mssTmt(),timeout()">

They are:

function startIt(){
    document.write('Timeout has started!');
}
function timeout(){
    function sleep(milliSeconds) {
        var startTime = new Date().getTime();
        var cnt=0;
        while (new Date().getTime() < startTime + milliSeconds){
            cnt++;
            if(cnt%1000000==0)
                console.log('time expired: '+(new Date().getTime())+'<br>');
        }
    }
    sleep(3000);
}
function mssTmt(){
    var greeting = 'Hello, I am awake!';
    document.write('<hr>'+greeting);
}

So I expected the following:

  1. It will be written 'Timeout has started!' on the page immediatelly after the page has been loaded.
  2. Next will be written 'Hello, I am awake!';
  3. And then the log generated within the loop in the function timeout will be outputed successively in console. But nothing of the kind. In reality the thing coming first is the loop in the function timeout(). So I see all those log messages and only after that I get messages in functions startIt() and mssTmt() written on the page. I must confess this is looks unusually for me. Why such a sequence? I have some presumption but of course it will be much better to get exact explanation from real JS guru! Plssss!

UPDATED after RoryKoehein answer I read the stuff that he gave me by link, but some things remain incomprehensible.

I changed my code a little. Now there is the caller:

function getStarted(){
    console.log(new Date().getTime()+' > getStarted() has been called');
  try{
    startIt();
    mssTmt();
timeout();
  }catch(e){
    alert(e.message);
  }
}

<a href="javascript:void();" onclick="getStarted();" id="getstarted">Get started!</a>

Instead

<body onLoad="startIt(),mssTmt(),timeout()"> 

First of all there such a thing happens: if I add an alert() just before every function is being called, the sequence is exactly the same as it placed in the code - startIt(),mssTmt(),timeout(). All implementations are blocked until I click on the alert popup. See the illustration please. If I remove alert, it works like earlier (see the starting point of the question). So if alert blocks ALL processes why it change an order of implementation (i/o)? Next I noticed a strange script behavior when I’m trying to call the function timeout() via setTimeout(); Here: http://javascript.info/tutorial/events-and-timing-depth#the-settimeout-func-0-trick is written that The setTimeout(.., 0) trick is used to execute the code after stacked events and fix timing-related problems. If I modify the code like this: setTimeout(timeout,[delay]); it proceeds unpredictable all the time:

  • if I set delay as 0, the it make output only after loop in the function timeout() is completed
  • if I increase delay, sometimes it make output (startIt(),mssTmt()) BEFORE loop, sometimes after, depending of delay value.

But the strangest thing is that that order of I/O became different during all those attempts even with the same delay value! For example: setTimeout(timeout,3); sometimes it results that first happens output in functions startIt(),mssTmt(), sometimes vice versa – timeout(). To be honest I have no idea what does it mean…

srgg6701
  • 1,498
  • 3
  • 19
  • 34

1 Answers1

1

This explains it pretty well: http://javascript.info/tutorial/events-and-timing-depth#javascript-execution-and-rendering

The most important thing being:

In most browsers, rendering and JavaScript use single event queue. It means that while JavaScript is running, no rendering occurs.

The while loop completely blocks the thread for three seconds. The document.write calls are added to the event queue, maybe even executed, but the paint-event happens after JS is not blocking anymore.

If you open Chrome's Developer Tools Timeline, you can see exactly what the browser is doing (https://developers.google.com/chrome-developer-tools/docs/timeline).

Off topic: I assume this is test code. In no way should anything like this be used in production. Stacking multiple functions inline within the body tag [1], using document.write [2] and the blocking while loop are all bad practice [3].

1 window.onload vs <body onload=""/> 2 Why is document.write considered a "bad practice"? 3 What is the JavaScript version of sleep()?

Community
  • 1
  • 1
RoryKoehein
  • 3,103
  • 1
  • 11
  • 12