waitForKeyElement.js 但有最长等待时间

waitForKeyElement.js But with a max wait time

当使用waitForKeyElement.js时,我想知道是否有一个好的解决方案来实现最长等待时间?有时我有一些应该存在的元素,但有时 ajax 响应不佳,它们不会出现,或者它们可能需要一段时间才能出现。在这种情况下,我只是希望它继续运行并执行一个单独的功能。

编辑:例如,当尝试 "buy" 一个项目时,它通常总是响应一个 "success" 框,这是程序正在等待的内容,但是有时如果服务器有错误,或者如果该项目不再可用于 "buy",在这种情况下,可能会插入一个不同的错误元素,但这是一个不同的元素,因此它继续等待而不是继续处理下一项。

该问题没有示例用例,也没有 MCVE。很有可能是 XY Problem.

就是说,没有优雅的方法来设置最长等待时间(因为以前从来没有这种需求,也没有这种需求)

您可以使用如下代码获得效果:

const maxTime       = 5;  //  seconds
var watchdogTimer   = setTimeout (fallBackFunc, maxTime * 1000);
waitForKeyElements ("#foo", desiredFunc, true);

function desiredFunc (jNode) {
    console.log ("Foo found!");
    clearTimeout (watchdogTimer);
}
function fallBackFunc () {
    console.log ("Oh, poo. No foo.");
}



在这种情况下卸载waitForKeyElements计时器应该是没有必要的,但您也可以通过在fallBackFunc()末尾添加以下代码来做到这一点:

function fallBackFunc () {
    console.log ("Oh, poo. No foo.");

    /*-- Optional body double to take fire from waitForKeyElements that the 
        has `true` parameter set.  This is almost never needed.
    */
    var nonce = "IdeallySomeGloballyUniqueStringThatIs_a_ValidCssClass";
    //-- Added node should have properties that match the WFKE selector
    $("body").append (`<span id="foo" class="${nonce}" style="display:none;">blah</span>`);
    setTimeout (function () {$(`.${nonce}`).remove(); }, 333); // time must be > 300
}


关于问题编辑:

... (the page) responds with a "success" box which is what the program is waiting for, however sometimes this box does not happen... in which case a different error element may be inserted instead...

通常的做法是设置 waitForKeyElements 来监听 成功节点和错误节点。 (参见 jQuery selectors doc。)

waitForKeyElementscallback 然后会针对传递给它的节点类型采取适当的操作。
不需要看门狗计时器(除非页面可以保持活动状态,但不是 return 任何一种节点类型——这几乎永远不会是这种情况)。

例如:

waitForKeyElements ("#goodNode, #errorNode", completeTransaction, true);

function completeTransaction (jNode) {
    if (jNode.is ("#goodNode") ) {  //  Match one of the WFKE selectores
        console.log ("Transaction success!");
    }
    else {
        console.log ("Transaction error.");
    }
}

作为奖励,这种方法:(A) 不必等待最大计时器 运行 结束,并且 (B) 如果最大计时器设置的时间不够长,则不会中断每一种情况。