I'm implementing functionality in Angular2 that requires the use of setTimeout
.
My code:
public ngAfterViewInit(): void {
this.authenticate_loop();
}
private authenticate_loop() {
setTimeout (() => {
console.log("Hello from setTimeout");
}, 500)
}
setTimeout
is started by ngAfterViewInit
but the loop is only executed once, eg. "Hello fromsetTimeout" is only printed once.
Question: How can I change the code to make the setTimeout work?
Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.
Option 1: Default the results. This is what I most commonly use. Option 2: Use Resolvers to load data before the component is initialized. A resolver is, basically, some code that runs before the route is loaded, and before the component is initialized.
Yes, that is perfectly fine to do.
Use the setInterval() method to call a function every N seconds in TypeScript, e.g. setInterval(myFunction, seconds * 1000) . The first parameter the method takes is the function that will be called on a timer, and the second parameter is the delay in milliseconds.
private authenticate_loop() {
setInterval (() => {
console.log("Hello from setInterval");
}, 500)
}
setTimeout
will run just one time, unless you create another setTimeout
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With