1
我正在使用setTimeout
可視化強化學習算法,並對其行爲感到好奇。setTimeout調用的順序
以下代碼顯示在while操作中使用的setTimeout。循環的每次迭代應使用state
版本,該版本已由前一次迭代修改。是否有可能第二次調用setTimeout會在第一次之前發生,並且狀態的值不會被正確更新?我問一部分原因是因爲我認爲我實際上已經注意到一些奇怪的行爲,當延遲時間太短時,doLearningInnerLoop調用的控制檯日誌出現故障(即時間= 1 4 3 2 5 6 ..等等)。
var doLearningInnerLoop = function(time, observedData, stateHolder, domain, sampleAction, selectModel, numSamples, depth, discount, stateQueries) {
console.log("new Round, time = " + time);
var state = stateHolder.state;
var currentModel = selectModel(observedData, 10, stateQueries);
var bestAction = sparseSampleMcmc(depth, numSamples, discount, currentModel, state, sampleAction, stateQueries);
var newStateReward = domain.executeAction(bestAction, stateQueries);
observedData.push(bestAction, newStateReward[1], newStateReward[0]);
stateHolder.state = newStateReward[0];
}
var doLearningLoops = function(time, observedData, state, domain, sampleAction, selectModel, numSamples, depth, discount, stateQueries) {
stateHolder = {};
stateHolder.state = state;
while(stateQueries['canContinue']['codeAsFunction'](time, stateHolder.state) === true) {
setTimeout(doLearningInnerLoop, 1000, time, observedData, stateHolder, domain, sampleAction, selectModel, numSamples, depth, discount, stateQueries);
time += 1;
}
return state;
}
不要擔心,JS中的定時器總是按順序執行。 – c69
我不知道這種行爲,但請注意,有[最小延遲](https://developer.mozilla.org/en/DOM/window.setTimeout#Minimum_delay_and_timeout_nesting)。如果你設置的延遲小於最小延遲,也許你會得到奇怪的結果。 – pimvdb