javascript - js callback 问题?
ringa_lee
ringa_lee 2017-04-10 15:40:20
[JavaScript讨论组]

在这里看到一个例子:

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.

ringa_lee
ringa_lee

ringa_lee

全部回复(1)
天蓬老师
  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判断原本的回调不会被执行。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号