有一种方法可以配置javascript的setInterval方法来立即执行该方法,然后与计时器一起执行
当前回答
你可以将setInterval()包装在提供该行为的函数中:
function instantGratification( fn, delay ) {
fn();
setInterval( fn, delay );
}
...然后这样使用它:
instantGratification( function() {
console.log( 'invoked' );
}, 3000);
其他回答
函数的即时异步调用存在一个问题,因为标准的setTimeout/setInterval即使直接将其设置为0,也具有大约几毫秒的最小超时。这是由浏览器特定的工作引起的。
一个具有REAL零延迟的代码示例,可在Chrome, Safari, Opera中工作
function setZeroTimeout(callback) {
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage('');
}
你可以在这里找到更多信息
在第一次手动调用之后,您可以用函数创建一个间隔。
为了解决这个问题,我在页面加载后第一次运行这个函数。
function foo(){ ... }
window.onload = function() {
foo();
};
window.setInterval(function()
{
foo();
}, 5000);
对于那些使用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]);
你可以将setInterval()包装在提供该行为的函数中:
function instantGratification( fn, delay ) {
fn();
setInterval( fn, delay );
}
...然后这样使用它:
instantGratification( function() {
console.log( 'invoked' );
}, 3000);
我不确定我是否理解正确,但你可以很容易地做这样的事情:
setInterval(function hello() {
console.log('world');
return hello;
}(), 5000);
显然有很多方法可以做到这一点,但这是我能想到的最简洁的方法。