有一种方法可以配置javascript的setInterval方法来立即执行该方法,然后与计时器一起执行
当前回答
如果你可以使用RxJS,有一个叫做timer()的东西:
import { Subscription, timer } from 'rxjs';
const INITIAL_DELAY = 1;
const INTERVAL_DELAY = 10000;
const timerSubscription = timer(INITIAL_DELAY, INTERVAL_DELAY)
.subscribe(() => {
this.updateSomething();
});
// when destroying
timerSubscription.unsubscribe();
其他回答
因为有人需要把外面的这个放在里面就像一个箭头函数一样。
(function f() {
this.emit("...");
setTimeout(f.bind(this), 1000);
}).bind(this)();
如果上面产生的垃圾困扰着你,你可以做一个闭包。
(that => {
(function f() {
that.emit("...");
setTimeout(f, 1000);
})();
})(this);
或者根据您的代码考虑使用@autobind装饰器。
对于那些使用React的人,下面是我解决这个问题的方法:
const intervalRef = useRef(0);
useEffect(() => {
if (condition is true){
if (intervalRef.current === 0) {
callMyFunction();
}
const interval = setInterval(() => {
callMyFunction();
}, 5_000);
intervalRef.current = interval;
} else {
clearInterval(intervalRef.current);
}
}, [deps]);
最简单的方法是自己第一次直接调用函数:
foo();
setInterval(foo, delay);
然而,有很好的理由避免setInterval——特别是在某些情况下,整个setInterval事件负载可以在彼此之后立即到达,没有任何延迟。另一个原因是,如果你想停止循环,你必须显式调用clearInterval,这意味着你必须记住从最初的setInterval调用返回的句柄。
因此,另一种方法是让foo在后续调用中使用setTimeout来触发自身:
function foo() {
// do stuff
// ...
// and schedule a repeat
setTimeout(foo, delay);
}
// start the cycle
foo();
这保证了调用之间至少有一个延迟间隔。如果需要的话,它还使取消循环变得更容易——当达到循环终止条件时,您不需要调用setTimeout。
更好的是,你可以把这一切都包装在一个立即调用的函数表达式中,它创建了函数,然后像上面一样再次调用自己,并自动启动循环:
(function foo() {
...
setTimeout(foo, delay);
})();
它定义了函数,并开始了整个循环。
我建议按以下顺序调用这些函数
var _timer = setInterval(foo, delay, params);
foo(params)
你也可以把_timer传递给foo,如果你想在特定的条件下清除interval (_timer)
var _timer = setInterval(function() { foo(_timer, params) }, delay);
foo(_timer, params);
我不确定我是否理解正确,但你可以很容易地做这样的事情:
setInterval(function hello() {
console.log('world');
return hello;
}(), 5000);
显然有很多方法可以做到这一点,但这是我能想到的最简洁的方法。