有一种方法可以配置javascript的setInterval方法来立即执行该方法,然后与计时器一起执行


当前回答

我不确定我是否理解正确,但你可以很容易地做这样的事情:

setInterval(function hello() {
  console.log('world');
  return hello;
}(), 5000);

显然有很多方法可以做到这一点,但这是我能想到的最简洁的方法。

其他回答

你可以在函数中设置一个非常小的初始延迟时间(例如100),并将其设置为你想要的延迟时间:

Var延迟= 100; 函数foo() { console.log("改变初始延迟时间为你想要的。"); 延迟= 12000; setTimeout (foo,延迟); }

如果你可以使用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装饰器。

/ / 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 hello() {
  console.log('world');
  return hello;
}(), 5000);

显然有很多方法可以做到这一点,但这是我能想到的最简洁的方法。