函数超时 (jQuery)

2023-12-02

function getNames(){
    // some code
}

这个功能可以在一秒钟内完成,但有时它会无限期地冻结自身和页面上的 html 块(ajax 内部)。

我希望这个功能有时间限制。如果十秒内没有完成,则中止它。

这个怎么做?


使用 jQuery 1.5 这真的很容易延期承诺.

以下示例创建一个 Deferred 并将两个基于计时器的函数设置为resolve or reject随机间隔后的 Deferred。无论哪个先触发“获胜”,并将调用其中一个回调。第二次超时没有效果,因为延迟已经从第一次超时操作完成(处于已解决或拒绝状态)。

// Create a Deferred and return its Promise
function asyncEvent() {
    var dfd = new jQuery.Deferred();
    setTimeout(function() {
        dfd.resolve('hurray');
    }, Math.floor(Math.random() * 1500));
    setTimeout(function() {
        dfd.reject('sorry');
    }, Math.floor(Math.random() * 1500));
    return dfd.promise();
}

// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(
    function(status) {
        alert( status + ', things are going well' );
    },
    function(status) {
        alert( status + ', you fail this time' );
    }
);

您可以轻松修改此示例以满足您的需求:

// Create a Deferred and return its Promise
function asyncEvent() {
    var dfd = new jQuery.Deferred();

    // Your asynchronous code goes here

    // When the asynchronous code is completed, resolve the Deferred:
    dfd.resolve('success');

    setTimeout(function() {
        dfd.reject('sorry');
    }, 10000); // 10 seconds
    return dfd.promise();
}

// Attach a done and fail handler for the asyncEvent
$.when( asyncEvent() ).then(
    function(status) {
        alert( status + ', things are going well' );
    },
    function(status) {
        alert( status + ', you fail this time' );
    }
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

函数超时 (jQuery) 的相关文章