在这里看到一个例子:
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. ?
如果在超时时限内被调用,则正常调用原本的回调
foo
。超过了超时时限,给
foo
抛一个错误,然后即使再被调用也不会执行foo
了。原本
ajax("xxx",foo)
的话,如果ajax
出了什么问题没有调用foo
那么你是无从得知的,也无法对此进行处理。而万一用户已经放弃了等待进行了一堆别的操作,ajax
过了一万年又突然跑回来调用了foo
,也有产生未知行为的危险。timeoutify
给回调加上了一层超时保护。set up a timeout that cancels the event. 可以理解为超时之后就不理会这个事件了。实际上只是看起来 cancels the event ,超时后回调(
timeoutify
返回的函数闭包)仍然被调用,只是因为那个if
判断原本的回调不会被执行。