我有一个简单的 Angular 可观察对象,它应该连续运行,检查每个循环的时间差,并每秒循环一次。当我运行它时,我收到“InternalError:太多递归”。据此:http://bonsaiden.github.io/JavaScript-Garden/#dealing-with-possible-blocking-code 我正在使用正确的方法。如何修复?
Angular 可观察:
export class MyService {
private lastHeartBeatTime = null; // Time of the last heartbeat
private heartBeatTimeoutId = null;
private secondsToHeartbeatAlert = 5; // Number of seconds of no heartbeat
constructor() {
this.lastHeartBeatTime = performance.now(); // Initialise local heartbeat variable with current time
}
subscribeToHeartbeat(callbackfn): any {
// Post a value via the observable to cause an alert to be raised:
if((performance.now() - this.lastHeartBeatTime) / 1000 >= this.secondsToHeartbeatAlert) return(true);
// Create a new timeout to call this function again after the specified num of milliseconds (e.g. after 1 second):
// **** PROBLEM HERE: ***
else this.heartBeatTimeoutId = setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);
}
}
另一个组件内的订阅:
// Subscribe to heartbeat over websockets:
MyService.subscribeToHeartbeat(this.handleHeartbeatFailure);
// Handler:
handleHeartbeatFailure:any = (message) => {
alert('Websocket is down!")
}
最佳答案
您正在调用该函数,但没有在超时时间内分配它
setTimeout(this.subscribeToHeartbeat(callbackfn), 1000);
需要
setTimeout(() => this.subscribeToHeartbeat(callbackfn), 1000);
或者你可以使用绑定(bind)
setTimeout(this.subscribeToHeartbeat.bind(this, callbackfn), 1000);
关于javascript - 如何避免 Angular observable 中的 "InternalError: too much recursion"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56399059/