我有一个通用的 Javascript 代码片段,所有客户都将其添加到他们的网站。此代码片段获取一个 JS 库,该库具有一些重要的函数,如果及时获取该库,则应调用这些函数。如果没有及时获取库,则永远不应调用这些函数。
为了实现这一点,我设置了一个超时,它有一个处理它的回调函数(它设置一个变量,取决于哪些重要函数将被调用或不被调用)。现在,它在大多数情况下都能完美运行,除非客户端的网站已经有一些超时/间隔且计时器值非常小。请参阅小提琴http://jsfiddle.net/tmckM/37/以查看问题。
我需要找到一种通用的方法来实现这一点,这样如果及时获取库,那么在任何情况下都不会发生超时。
以下是 JSFiddle 中使用的代码
//Though the library file is downloaded in time(which can be seen from network tab) but still the timeout fires before the library execution. I need to find a workaround for this issue
var library_timeout = 1000;
//All time values are in milliseconds
function loadLibrary() {
var b = document.createElement('script');
b.src = 'http://yourjavascript.com/35211527623/library.js';
b.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(b);
}
function wasteTime() {
if (!wasteTime.counter) {
wasteTime.counter = 1;
}
else {
wasteTime.counter++;
}
if (wasteTime.counter == 5) {
clearInterval(wasteTimerId);
}
console.warn('Start wasting time');
var initial = Date.now();
while (true) {
if (Date.now() - initial > 1000) {
break;
}
}
console.warn('Stopped wasting time');
}
function startProcess() {
window.process_started_at = Date.now();
console.log('Started the process at timestamp:', process_started_at);
setTimeout(function () {
window.lib_timeout_fired_at = Date.now();
console.log('Library timed out at timestamp:', lib_timeout_fired_at);
console.log('So, though the library file will still download, but the functions in it won\'t be called.');
}, library_timeout);
loadLibrary();
}
//The following line is implemented on user's website.I can't change it.
wasteTimerId = setInterval(wasteTime, 0);//If this line is skipped then library is always executed first and then timeout occurs.
startProcess();