2013-02-25 18 views
0

我有一個通用的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(); 
+0

所以'wasteTime'函數只是代替客戶端網站上執行的實際代碼? – Bergi 2013-02-25 13:41:44

+0

@Bergi是的,它僞造客戶的代碼。 – hariom 2013-02-26 09:13:37

回答

0

使用我沒有看到一個問題,這裏的代碼。 lib加載時間可能會有所不同,wasteTime js加載可能會有所不同,並且so can timeouts。瀏覽器可以非常自由地首先執行加載的腳本,或者如果兩者都被調度,則觸發超時。

對此的解決方案根本不使用超時。只需在您的庫腳本改變

if(window.lib_timeout_fired_at) 

來(你有所有的變量繳費的話):

if (lib_started_at - process_started_at > library_timeout) 

當然,你可能會重命名/前綴他們,所以整體解決方案可能看起來像

window.lib_timeout_firing_at = Date.now() + 1000; 
… 
if (Date.now() > lib_timeout_firing_at) 
+0

我忘了提及,有一個回退函數(撤消由startProcess對DOM所做的更改),該函數在間隔內未加載庫時調用。所以,這就是爲什麼我認爲setTimeout是必要的,因爲它可能是庫服務器關閉和庫文件永遠不會來的情況。 – hariom 2013-02-26 09:13:05

+0

然後你的超時解決方案很好。我認爲你不能可靠地區分「lib被及時提取但尚未執行」和「lib尚未加載」;你只能提高超時值。 – Bergi 2013-02-26 14:41:09

相關問題