有一种方法可以配置javascript的setInterval方法来立即执行该方法,然后与计时器一起执行
当前回答
我不确定我是否理解正确,但你可以很容易地做这样的事情:
setInterval(function hello() {
console.log('world');
return hello;
}(), 5000);
显然有很多方法可以做到这一点,但这是我能想到的最简洁的方法。
其他回答
因为有人需要把外面的这个放在里面就像一个箭头函数一样。
(function f() {
this.emit("...");
setTimeout(f.bind(this), 1000);
}).bind(this)();
如果上面产生的垃圾困扰着你,你可以做一个闭包。
(that => {
(function f() {
that.emit("...");
setTimeout(f, 1000);
})();
})(this);
或者根据您的代码考虑使用@autobind装饰器。
这个例子建立在@Alnitak的回答上,但是使用await Promise在循环循环中进行更细粒度的控制。
比较的例子:
let stillGoing = true;
(function foo() {
console.log('The quick brown fox did its thing');
if (stillGoing) setTimeout(foo, 5000);
})();
foo();
在上面的例子中,我们调用foo(),然后它每5秒调用一次自己。
但是如果,在未来的某个时候,我们为了停止循环而将stillGoing设为false,即使在发出停止命令之后,我们仍然会得到一个额外的log行。这是因为在任何给定的时间,在我们将stillGoing设置为false之前,当前迭代将已经创建了一个超时来调用下一次迭代。
如果我们使用await Promise作为延迟机制,那么我们就有机会在调用下一次迭代之前停止循环:
let stillGoing = true;
(async function foo() {
console.log('The quick brown fox did its thing');
await new Promise(resolve => setTimeout(resolve, 5000));
if (stillGoing) foo();
})();
foo();
在第二个示例中,我们首先设置5000ms的延迟,之后检查stillGoing值并决定是否调用另一个递归是合适的。
如果我们在任意点将stillGoing设为false,在我们设置值之后就不会打印出额外的log行。
需要注意的是,这要求函数是异步的,对于给定的使用,这可能是也可能不是一个选项。
/ / YCombinator 匿名函数(fnc) { 返回函数(){ fnc。应用(fnc参数); 返回fnc; } } //第一次调用: setInterval(匿名函数(){ console.log(“酒吧”); }) (), 4000); //不调用第一次: setInterval(匿名函数(){ console.log (" foo "); }), 4000); //或者简单: setInterval(函数(){ console.log(“巴兹”); }, 4000);
好吧,这太复杂了,让我说得简单点:
函数hello(status) { console.log(‘世界’,+ + status.count); 返回状态; } setInterval(hello, 5 * 1000, hello({count: 0}));
你可以将setInterval()包装在提供该行为的函数中:
function instantGratification( fn, delay ) {
fn();
setInterval( fn, delay );
}
...然后这样使用它:
instantGratification( function() {
console.log( 'invoked' );
}, 3000);
我建议按以下顺序调用这些函数
var _timer = setInterval(foo, delay, params);
foo(params)
你也可以把_timer传递给foo,如果你想在特定的条件下清除interval (_timer)
var _timer = setInterval(function() { foo(_timer, params) }, delay);
foo(_timer, params);