我最近遇到了一个相当讨厌的错误,其中代码是<select>通过JavaScript动态加载的.这种动态加载<select>具有预先选择的值.在IE6中,我们已经有了修复所选内容的代码<option>,因为有时它<select>的selectedIndex值与所选<option>的index属性不同步,如下所示:
field.selectedIndex = element.index;
Run Code Online (Sandbox Code Playgroud)
但是,此代码无效.即使selectedIndex正确设置了字段,最终也会选择错误的索引.但是,如果我alert()在正确的时间插入声明,则会选择正确的选项.考虑到这可能是某种时间问题,我尝试了一些随机的东西,我之前在代码中看到过:
var wrapFn = (function() {
var myField = field;
var myElement = element;
return function() {
myField.selectedIndex = myElement.index;
}
})();
setTimeout(wrapFn, 0);
Run Code Online (Sandbox Code Playgroud)
这有效!
我已经找到了解决问题的方法,但是我很不安,因为我不知道为什么这会解决我的问题.有人有官方解释吗?使用"稍后"调用我的功能可以避免哪些浏览器问题setTimeout()?
在Google Drive API的快速入门指南中,一旦加载了客户端库,就会调用以下函数:
// Called when the client library is loaded to start the auth flow.
function handleClientLoad() {
window.setTimeout(checkAuth, 1);
}
Run Code Online (Sandbox Code Playgroud)
setTimeout以这样的延迟1呼叫而不是checkAuth立即呼叫的目的是什么?
我有一个相当长的运行(3到10秒)函数,它在后台加载数据,用于页面中相当不常用的部分.我的问题是每次执行的最佳运行时间和确保页面其余部分保持相当交互的延迟时间是多少,但是通过分解数据加载不会过度延迟?
例如:
var i = 0;
var chunkSize = 10;
var timeout = 1;
var data; //some array
var bigFunction = function() {
var nextStop = chunkSize + i; //find next stop
if (nextStop > data.length) { nextStop = data.length }
for (; i < nextStop; i++) {
doSomethingWithData(data[i]);
}
if (i == data.length) { setTimeout(finalizingFunction, timeout); }
else { setTimeout(bigFunction , timeoutLengthInMs); }
};
bigFunction(); //start it all off
Run Code Online (Sandbox Code Playgroud)
现在,我已经完成了一些测试,并且chunkSize产生大约100毫秒的执行时间和1毫秒timeout似乎产生了非常灵敏的UI,但是我见过的一些例子推荐更大的块(~300毫秒)和更长的超时(20到100毫秒).我是否错过了将我的功能削减到太多小块的危险,或者试错是一种确定这些数字的安全方法?
我在页面上有多个document.ready函数,我希望在执行所有document.ready函数时调用一个函数.我只是希望在所有其他document.ready函数执行完毕后,在最后调用该函数.一个例子可能是每个document.ready函数在执行时递增一个全局变量,最后一个函数需要在最后检查该变量的值.
有任何想法吗 ?