admin管理员组

文章数量:1188795

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?

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?

Share Improve this question edited May 23, 2017 at 10:31 CommunityBot 11 silver badge asked Apr 21, 2012 at 10:10 Umesh MoghariyaUmesh Moghariya 3,1836 gold badges22 silver badges24 bronze badges 2
  • 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 Commented Apr 21, 2012 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 Commented Apr 21, 2012 at 10:15
Add a comment  | 

4 Answers 4

Reset to default 16

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
})

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);

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" />

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?

本文标签: Does Javascript setTimeout stop other script executionStack Overflow