Javascript setTimeout是否会停止其他脚本执行

时间:2012-04-21 10:10:18

标签: javascript

我指的是this。一切都还不清楚。

  • 我有一个更新树的JS函数fillTree(),它有复选框。
  • 我有另一个函数checkSelectedBoxes(),它在window.onload上执行,检查所选的复选框。
  • 现在连接了很多其他功能。

我的问题:

  • 如果我使用setTimeout(),其他脚本功能是否也会停止并等待我的功能完成加载?

这可能是这种情况:

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

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

即使增加时间间隔,也会返回空值。 fillTree()暂停执行吗?

3 个答案:

答案 0 :(得分:13)

不,setTimeout不等你(因此,JS没有暂停功能)。 setTimeout做的是稍后将该任务放在一边,并允许执行下一行。当超时达到时,它会将该任务插入执行行。当没有其他代码正在运行时,它会执行指示的函数。

您要做的是给fillTree()回调并在完成后执行。

function fillTree(callback){

    //do something very long

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

fillTree(function(){
    checkSelectedBoxes(); //executes only when fillTree finishes
})

答案 1 :(得分:2)

  

它是我正在使用的CMS,并且树被设置在其他js文件中,我不会干涉,因为它使用了许多其他功能,并且案例可能并不总是相同

如果无法修改fillTree()函数,可以将其包装在自己的函数中并对其应用回调函数。试试这个:

function doStuff(callback) {
    fillTree();

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

doStuff(checkSelectedBoxes);

答案 2 :(得分:0)

setTimeout函数不会等待执行,您可以在以下代码段中清楚地检查它。您可以看到,在给定随机时间数组waitTimes的情况下,Array.map函数将首先打印出所有time[index]=waitTimes[index]值,然后在wait[index]=waitTimes[index]时打印setTimeoutwaitTimes[index]毫秒后完全触发。

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