有一种方法可以配置javascript的setInterval方法来立即执行该方法,然后与计时器一起执行
当前回答
因为有人需要把外面的这个放在里面就像一个箭头函数一样。
(function f() {
this.emit("...");
setTimeout(f.bind(this), 1000);
}).bind(this)();
如果上面产生的垃圾困扰着你,你可以做一个闭包。
(that => {
(function f() {
that.emit("...");
setTimeout(f, 1000);
})();
})(this);
或者根据您的代码考虑使用@autobind装饰器。
其他回答
你可以将setInterval()包装在提供该行为的函数中:
function instantGratification( fn, delay ) {
fn();
setInterval( fn, delay );
}
...然后这样使用它:
instantGratification( function() {
console.log( 'invoked' );
}, 3000);
为了解决这个问题,我在页面加载后第一次运行这个函数。
function foo(){ ... }
window.onload = function() {
foo();
};
window.setInterval(function()
{
foo();
}, 5000);
因为有人需要把外面的这个放在里面就像一个箭头函数一样。
(function f() {
this.emit("...");
setTimeout(f.bind(this), 1000);
}).bind(this)();
如果上面产生的垃圾困扰着你,你可以做一个闭包。
(that => {
(function f() {
that.emit("...");
setTimeout(f, 1000);
})();
})(this);
或者根据您的代码考虑使用@autobind装饰器。
我不确定我是否理解正确,但你可以很容易地做这样的事情:
setInterval(function hello() {
console.log('world');
return hello;
}(), 5000);
显然有很多方法可以做到这一点,但这是我能想到的最简洁的方法。
如果你可以使用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();