2

I am new to javascript and observed that the 2 functions in body tag onload="expand();fadeOut();" at link http://jsfiddle.net/ankur3291/F8pXj/6/ are in serial order so must be executed one by one, but when seeing the result it seems that both the functions are running simultaneously. Why is it so? Why not they execute one by one serially? (plz do not try to update the code at specified link....because the link will then change) Also see the code below:

<html>
<head>
<title>dimensions</title>
<style type='text/css'>
body{margin:0;}
.box{display:block;background-color:green;}
#container{height:100px;width:100px;position:relative;top:150px;left:150px;}
#contain{display:block;position:fixed;height:200px;width:200px;top:100px;left:100px;font-size:50px;t

ext-align:center;line-height:200px;opacity:0;background-color:orange;}
</style>
<script type='text/javascript'>

function expand(){
    var obj=document.getElementById("container");
    var h=100
    var w=100
    var t=150
    var l=150       

    function frame()
    {    
        t=t-2;
        l=l-1.97*2;
        h=h+4;
        w=w+1.96*4;

            obj.style.height=h+'px';
        obj.style.width=w+'px';
        obj.style.top=t+'px';
        obj.style.left=l+'px';

        if(t<=5 || l<=5)
            clearInterval(timer);
    }
    var timer=setInterval(frame,1);
}
function fadeOut(){
    var obj=document.getElementById("contain");
    var o=0;
    function frame(){
        obj.style.opacity=o;
        o=o+0.01;
        if(o>=1)
            clearInterval(timer);
    }
    var timer=setInterval(frame,1);
}
</script>
</head>
<body onload="expand();fadeOut();">
<div class="box" id="container">
</div>
<div id="contain">
 Unicorn
</div>
</body>
</html>
Ankur Shah
  • 801
  • 1
  • 12
  • 26

2 Answers2

3

This is due to the way that setInterval works. Both functions set an interval that is to be called every millisecond (although it's highly likely it will actually be called less frequently).

In your example, both functions schedule their update functions to be run using setInterval. The functions defined in the onload attribute of the body tag are called sequentially; however, the chunking of the animations into small pieces makes it look like they are run in parallel which is never the case due to JavaScript's inherent single-threaded nature.

As a very broad rule of thumb, you can compare the way this works to a single-threaded process scheduler which alternates between several processes very quickly. Only one process runs at any given moment, but the frequent changing of the active process creates the illusion of parallelism.

Marius Schulz
  • 15,976
  • 12
  • 63
  • 97
  • now I am really getting more confused, some people are saying (to whom I talked) that javascript is multi-threaded but you are saying that it is single threaded in nature. Can you plz provide me any proof regarding this? Moreover, as you said "chunking of animations"...If I am not wrong you are saying it for the setInterval() statements, are not these functions running at once, if they run at once, the two functions will not seem to run parallel, or is it like now there are two threads for each setInterval statement and they are switching in few milli-seconds for execution ? Plz clarify this! – Ankur Shah Jul 24 '13 at 13:56
  • @AnkurShah JavaScript execution runs in a single thread as John Resig explains in http://ejohn.org/blog/how-javascript-timers-work/. He also explains how `setInterval` and `setTimeout` work, so make sure to read his post. If you want more information on how the only asynchronous feature (which is *events*) works, check out the very detailed first answer to this question: http://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded – Marius Schulz Jul 24 '13 at 22:16
0

Your function calls do execute consecutively. However, they both execute the first iteration, set an Interval and exit, so the second and subsequent iterations will both be called by your timers, and appear to execute concurrently. if you want consecutive execution then call the second function from the first, after the first timer has counted out.

  • Is javascript multi-threaded in nature?...I got what you said but in terms of multi-threading that both the timers act as a thread and after both the functions finished being processed at once the timer threads switch their processes to execute and seem to run concurrently. Is my interpretation correct or not? Plz reply... – Ankur Shah Jul 24 '13 at 14:07
  • Javascript is single-threaded, but that's not relevant here. Your problem derives from the asynchronous nature of the timers. Don't confuse 'asynchronous' with 'multi-threaded'. –  Jul 29 '13 at 09:25