14

I am referring to this. Everything is still not clear.

  • I have a JS function fillTree() which updates a tree, it has checkboxes.
  • I have another function checkSelectedBoxes() which is executed on window.onload which checks for selected checkboxes.
  • Now there are lots of other functions connected.

My question:

  • If I am using setTimeout() will the other script function also stop and wait for my function to finish loading?

What might be the case in this:

function fillTree(){...}
function checkSelectedBoxes(){...}

fillTree(); // This take time to get data. onLoad() doesnt work.
setTimeout(function(){ checkSelectedBoxes()  },5000);

This returns me null values even after increasing the time interval. Does fillTree() pause execution?

Community
  • 1
  • 1
Umesh Moghariya
  • 3,063
  • 6
  • 21
  • 23
  • No, `setTimeout` does not pause execution of other code. If you're trying to call `checkSelectedBoxes()` on completion of `fillTree()` why not pass it as a callback parameter, or simply at the end of `fillTree()`? – Rory McCrossan Apr 21 '12 at 10:13
  • @RoryMcCrossan thanks, your answer seems the best possible solution but its a CMS i am using and the tree is set in some other js file which I am not to interfere with as it is used many other functions and the cases may not be always same – Umesh Moghariya Apr 21 '12 at 10:15

4 Answers4

15

No, setTimeout does not wait for you (hence, JS has no pause function). What setTimeout does is set aside that task at a later time, and allow the next line to be executed. when that timeout is reached , it inserts that task into the execution line. and when no other code is running, it executes the function that was indicated.

what you want to do is give a callback to your fillTree() and execute when it's done.

function fillTree(callback){

    //do something very long

    callback(); //execute passed function when it's done
}

fillTree(function(){
    checkSelectedBoxes(); //executes only when fillTree finishes
})
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Thanks. That cleared Everything. I will accept in 8 mins :P. Also the question doesnt state so, but could you advice me such case as to what should be my approach? – Umesh Moghariya Apr 21 '12 at 10:17
  • what does fillTree do exactly? is it an Ajax call? DOM walking? what takes so long? – Joseph Apr 21 '12 at 10:18
  • 3
    "it inserts that task into the execution line" is not fully accurate. It will not interrupt user code nor run this concurrently; it will only run when no JS user code is running and the timeout has been reached. – Lucero Apr 21 '12 at 10:19
  • good point. but simply speaking, it's like that. i'll update it. – Joseph Apr 21 '12 at 10:21
  • 2
    It is a very important aspect since this allows the programmer to make assuptions on reentrancy (e.g. it will not reenter). – Lucero Apr 21 '12 at 10:22
2

its a CMS i am using and the tree is set in some other js file which I am not to interfere with as it is used many other functions and the cases may not be always same

If the fillTree() function cannot be modified you can wrap it in your own function and apply a callback function to that. Try this:

function doStuff(callback) {
    fillTree();

    // Call the callback parameter (checkSelectedBoxes() in this case)
    // when fillTree() has completed
    callback();
}

doStuff(checkSelectedBoxes);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

The setTimeout function does not wait execution and you can clearly check it in the following snippet. You can see how, given the array waitTimes of random times, the Array.map function will print out first all the time[index]=waitTimes[index] values, then the wait[index]=waitTimes[index] when the setTimeout is fired exactly after waitTimes[index] milliseconds.

var console = {
  log: function(s) {
    document.getElementById("console").innerHTML += s + "<br/>"
  }
}
var roundDecimals = function(num, pos) {
  pos = pos || 4;
  return (Math.round(num * Math.pow(10, pos)) / Math.pow(10, pos));
}
var arrayRangeMap = function(a, block) {
  c = [];
  while (a--) c[a] = block();
  return c
};
var getRandomArbitrary = function(min, max) {
    return (Math.random() * (max - min) + min);
  }
  // random 10 wait times, 3 decimal positions
var waitTimes = arrayRangeMap(10, function() {
  return roundDecimals(getRandomArbitrary(0.250, 0.5, 3) * 1000, 2);
});

waitTimes.map(function(item, index) {
  setTimeout(function() {
    console.log("wait[" + index + "]=" + item);
  }, item);
  console.log("time[" + index + "]=" + item);
});
<div id="console" />
loretoparisi
  • 15,724
  • 11
  • 102
  • 146
0

I just made a test which may be of interest:

<!DOCTYPE html>
<html>
  <head>
    <script>

/* test: if returns in around 1000ms, must interrupt, otherwise it is indeed
   not going to let timeout work until work is done. */    
window.onload = function() {
    var before = performance.now();
    setTimeout(function() {
        alert('completed in ~' + (performance.now() - before) + ' nanoseconds.');
    }, 1000);

    /* count to 2^31 - 1... takes 8 seconds on my computer */
    for (var i = 0; i < 0xffffffff; ++i) {
        /* me busy, leave me alone */ 
    }
};      
    </script>
  </head>
  <body>
  </body>
</html>

I'm now really curious how JavaScript knows when certain amount of time has elapsed. Does it spawn a thread that sleeps for a period of time? And if so is there a limit on how many threads sleep, or are sleeping threads "stored" until they are needed? Much confuse.

I think it has something to do with

"If it doesn't need to be exactly 1s, then just usleep a second. usleep and sleep put the current thread into an efficient wait state that is at least the amount of time you requested (and then it becomes eligible for being scheduled again).

If you aren't trying to get near exact time there's no need to check clock()."

--pthread sleep function, cpu consumption

So I guess the operating system does the scheduling for you, at which point it interrupts the engine, and the engine stops the world and puts the timeout function on top of the queue to be executed as soon as possible?

Community
  • 1
  • 1
Dmytro
  • 5,068
  • 4
  • 39
  • 50