首页 > js callback 问题?

js callback 问题?

在这里看到一个例子:

What about the trust issue of never being called? If this is a concern
(and it probably should be!), you likely will need to set up a timeout
that cancels the event. You could make a utility (proof-of-concept
only shown) to help you with that:

function timeoutify(fn,delay) {
    var intv = setTimeout( function(){
            intv = null;
            fn( new Error( "Timeout!" ) );
        }, delay )
    ;

    return function() {
        // timeout hasn't happened yet?
        if (intv) {
            clearTimeout( intv );
            fn.apply( this, arguments );
        }
    };
}

Here's how you use it:

// using "error-first style" callback design
function foo(err,data) {
    if (err) {
        console.error( err );
    }
    else {
        console.log( data );
    }
}

ajax( "http://some.url.1", timeoutify( foo, 500 ) );

请问:
1.timeoutify解决了什么问题?(我能看懂代码)
2.如何理解 set up a timeout that cancels the event.


  1. 如果在超时时限内被调用,则正常调用原本的回调foo

  2. 超过了超时时限,给foo抛一个错误,然后即使再被调用也不会执行foo了。

原本ajax("xxx",foo)的话,如果ajax出了什么问题没有调用foo那么你是无从得知的,也无法对此进行处理。而万一用户已经放弃了等待进行了一堆别的操作,ajax过了一万年又突然跑回来调用了foo,也有产生未知行为的危险。

timeoutify给回调加上了一层超时保护。

set up a timeout that cancels the event. 可以理解为超时之后就不理会这个事件了。实际上只是看起来 cancels the event ,超时后回调(timeoutify返回的函数闭包)仍然被调用,只是因为那个if判断原本的回调不会被执行。

【热门文章】
【热门文章】