【发布时间】:2016-05-27 19:14:20
【问题描述】:
我有一个具有以下基本设置的项目...(我将其剥离为仅必要的部分,但引擎对象中除了 setHtml 之外还有其他功能)
var engine = {
setHtml:function(){
htmlGenerator(callback)
//if htmlGenerator takes 5 or more seconds to respond, skip the item.
//Otherwise, continue with regular flow
function skip(){
//skip the current item
}
function callback(){
//continue with regular flow
}
}
}
看起来很简单,但也有一些挑战......
htmlGenerator 位于另一个文件中。我无法知道该函数是同步的还是异步的,理想情况下这并不重要。
htmlGenerator 准备好后会调用 callback()。
应该调用 skip() 或 callback() 中的一个,而不是两者都调用。
如果htmlGenerator调用回调的时间超过5s,我想调用skip()。这并不意味着 htmlGenerator 不会调用 callback()。
skip() 可能会被递归调用,但无法确定它是否会被递归调用。 (即跳过调用的一部分是使用一组新数据再次调用 setHtml,这可能会或可能不会导致另一个调用需要 5 秒或更长时间)
这是一个前端应用程序,因此我希望尽可能避免引入额外的库/模块/包,因为加载时间是重中之重。
有一段时间,我有类似以下的情况,但由于我无法解释的原因,它不起作用。
var engine = {
skipTimer:null
setHtml:function(){
htmlGenerator(callback)
//if htmlGenerator takes 5 or more seconds to respond, skip the item.
//Otherwise, continue with regular flow
engine.skipTimer = setTimeout(skip,5000)
function skip(){
console.log(engine.skipTimer)//this would correctly display the timer's ID.
//skip the current item
}
function callback(){
console.log(engine.skipTimer)//this was "false" or "null" or something to that effect
clearTimeout(engine.skipTimer) //for some reason, the timer was never cleared
//continue with regular flow
}
}
}
在我的测试用例中,我没有调用多次失败(跳过)的函数,但我确实需要它来处理它。
我也尝试了以下方法,但收效甚微......
var engine = {
setHtml:function(){
var called = false;
htmlGenerator(callback)
//if htmlGenerator takes 5 or more seconds to respond, skip the item.
//Otherwise, continue with regular flow
engine.skipTimer = setTimeout(skip,5000)
function skip(){
if (called)return;
called = true;
//skip the current item
}
function callback(){
if(called)return;
called = true;
//continue with regular flow
}
}
}
如果您了解这些结果失败的原因,或者如何解决此问题,我们将不胜感激。
【问题讨论】:
-
如果
htmlGenerator是同步的,则无法通过超时停止它, -
如果 htmlGenerator 是同步的,那么计时器应该无关紧要。我总会及时获得价值。
标签: javascript jquery asynchronous settimeout