繁体   English   中英

当页面上存在其他setTimeout / setInterval调用时,setTimeout问题

[英]Issue with setTimeout, when other setTimeout/setInterval calls are present on a page

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

我在这里看不到问题。 库的加载时间可以变化, wasteTime js的加载可以变化, 超时也可以变化。 浏览器可能很自由,可以先执行加载的脚本,也可以在计划了两者的情况下触发超时。

解决方案根本不使用超时。 只需更改

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM