我有一個通用的JavaScript代碼片段,所有的客戶端添加到他們的網站。這段代碼片段提取了一個JS庫,它具有一些重要的功能,如果庫及時提取,應該調用這些功能。如果庫沒有及時提取,那麼這些函數不應該被調用。setTimeout問題,當其他setTimeout/setInterval調用存在於一個頁面
爲了實現這個,我設置了一個具有回調函數的超時函數,該函數負責處理它(根據哪些重要函數將被調用或不調用而設置一個變量)。現在,在大多數情況下,除非客戶的網站已經有一些具有非常小的計時器值的超時/間隔,否則它可以很好地工作。 請看小提琴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();
所以'wasteTime'函數只是代替客戶端網站上執行的實際代碼? – Bergi 2013-02-25 13:41:44
@Bergi是的,它僞造客戶的代碼。 – hariom 2013-02-26 09:13:37