There's many questions and solutions in SO but none of them work when called from componenent init which is not async. Here's an example:
private delay(ms: number)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
private async sleepExample()
{
console.log("Beforep: " + new Date().toString());
// Sleep thread for 3 seconds
await this.delay(3000);
console.log("Afterp: " + new Date().toString());
}
ngOnInit(): void {
console.log('ngOnInit');
this.sleepExample();
console.log('After sleep');
// do lots of stuff
console.log('After lots of stuff);
}
The console output looks like this:
ngOnInit
Beforep: Mon Mar 18 2019 21:22:58 GMT+0200 (Eastern European Standard Time)
After sleep
…
After lots of stuff
Afterp: Mon Mar 18 2019 21:23:02 GMT+0200 (Eastern European Standard Time)
How to sleep in ngOnInit? The reason I'm asking is that I'm trying to prototype a multiple window application that communicates with localStorage. 1st window started becomes main window. When I start 2 windows at almost same time the latter won't yet find the 1st window's stuff in localStorage and thinks it is also mainWindow. So logical solution would be to wait for 1-2 secs and try to read the localStorage again if the window didn't find anything. After "sleep" the 2nd window would find out that there actually was already a window and it becomes childwindow.