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


当前回答

你可以将setInterval()包装在提供该行为的函数中:

function instantGratification( fn, delay ) {
    fn();
    setInterval( fn, delay );
}

...然后这样使用它:

instantGratification( function() {
    console.log( 'invoked' );
}, 3000);

其他回答

在ES2017中,最好完全避免使用setInterval。

下面的解决方案具有更清晰的执行流程,可以防止函数需要比预期时间更长的时间才能完成的问题,并允许异步操作。

const timeout = (delayMs) => new Promise((res, _rej) => setTimeout(res, delayMs));

const DELAY = 1_000;

(async () => {
  while (true) {
    let start_time = Date.now();

    // insert code here...

    let end_time = Date.now();
    await timeout(DELAY - (end_time - start_time));
  }
})();

如果你可以使用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 foo(){ ... }

window.onload = function() {
   foo();
};

window.setInterval(function()
{
    foo(); 
}, 5000);

你可以将setInterval()包装在提供该行为的函数中:

function instantGratification( fn, delay ) {
    fn();
    setInterval( fn, delay );
}

...然后这样使用它:

instantGratification( function() {
    console.log( 'invoked' );
}, 3000);

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

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

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