[英]Javascript pattern for callback timeout with setTimeout?
On page load I setup some functions and call the first one which is supposed to go through step by step. 在页面加载时,我设置了一些功能并调用了应该逐步进行的第一个功能。
after5Seconds();
function after5Seconds() {
setTimeout(hideOne, 5000);
}
function hideOne() {
$('.toggleme#one').fadeOut(showTwo);
}
function showTwo() {
$('.toggleme#two').fadeIn('125', 'swing', startAllOver);
}
I'm finding that often some callbacks get stalled and fail silently and i'm starting to update each to be more like: 我发现有些回调经常停滞不前,并且无声地失败,而我开始将每个回调更新为:
Something like: 就像是:
function wrapMeInDelay(fn, timer) {
var hasBeenCalled = false;
var ctx = function() {
if (hasBeenCalled) {
return false;
} else {
hasBeenCalled = true;
return fn();
}
};
setTimeout(ctx, timer);
return ctx;
}
basically I want to start adding timeouts to the callbacks to make sure they are called if the jquery/whatever callback doesn't trigger it first. 基本上,我想开始向回调添加超时,以确保如果jquery /无论哪种回调都没有首先触发它,都将调用它们。
Is there another more common way of doing this i'm not aware of? 还有我不知道的另一种更常见的方式吗?
If I understand you correctly, you want to call some function after X seconds only if this function is not already called? 如果我理解正确,那么仅在尚未调用此函数的情况下,才想在X秒后调用某个函数?
var _timeout;
function onTrigger(){
if (_timeout){
clearTimeout(_timeout);
};
console.log("function triggered");
};
_timeout = setTimeout(onTrigger, 5000);
onTrigger();
You need to store in variable reference to that timeout, and when function is called, remove that timeout (clearTimeout). 您需要在变量引用中存储对该超时的引用,并在调用函数时删除该超时(clearTimeout)。 In that case timeout will not be executed.
在这种情况下,将不会执行超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.