有一种方法可以配置javascript的setInterval方法来立即执行该方法,然后与计时器一起执行
当前回答
因为有人需要把外面的这个放在里面就像一个箭头函数一样。
(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}));
如果你需要,这里有一个包装来美化它:
(function() {
var originalSetInterval = window.setInterval;
window.setInterval = function(fn, delay, runImmediately) {
if(runImmediately) fn();
return originalSetInterval(fn, delay);
};
})();
将setInterval的第三个参数设置为true,它将在调用setInterval后立即运行:
setInterval(function() { console.log("hello world"); }, 5000, true);
或者省略第三个参数,它将保持原来的行为:
setInterval(function() { console.log("hello world"); }, 5000);
一些浏览器支持setInterval的附加参数,但这个包装器没有考虑到这些参数;我认为这些很少使用,但如果你确实需要它们,请记住这一点。
你可以将setInterval()包装在提供该行为的函数中:
function instantGratification( fn, delay ) {
fn();
setInterval( fn, delay );
}
...然后这样使用它:
instantGratification( function() {
console.log( 'invoked' );
}, 3000);
由于同样的问题,我偶然发现了这个问题,但如果你需要完全像setInterval()那样运行,那么没有一个答案可以帮助你,唯一的区别是函数在开始时立即被调用。
以下是我对这个问题的解决方案:
function setIntervalImmediately(func, interval) {
func();
return setInterval(func, interval);
}
该解决方案的优点:
使用setInterval的现有代码可以很容易地通过替换进行调整 在严格模式下工作 它使用现有的命名函数和闭包 您仍然可以使用返回值并稍后将其传递给clearInterval()
例子:
// create 1 second interval with immediate execution
var myInterval = setIntervalImmediately( _ => {
console.log('hello');
}, 1000);
// clear interval after 4.5 seconds
setTimeout( _ => {
clearInterval(myInterval);
}, 4500);
坦率地说,如果你真的需要使用setInterval,那么你也可以替换原来的setInterval。因此,在现有代码之前添加此代码时不需要更改代码:
var setIntervalOrig = setInterval;
setInterval = function(func, interval) {
func();
return setIntervalOrig(func, interval);
}
尽管如此,上面列出的所有优点都适用于这里,但没有必要进行替换。
因为有人需要把外面的这个放在里面就像一个箭头函数一样。
(function f() {
this.emit("...");
setTimeout(f.bind(this), 1000);
}).bind(this)();
如果上面产生的垃圾困扰着你,你可以做一个闭包。
(that => {
(function f() {
that.emit("...");
setTimeout(f, 1000);
})();
})(this);
或者根据您的代码考虑使用@autobind装饰器。