Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: setTimeout only called once

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?

like image 632
Vingtoft Avatar asked Nov 03 '16 13:11

Vingtoft


People also ask

How do you call every 10 seconds in angular 8?

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.

What we can use instead of setTimeout in angular?

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.

Is it okay to use setTimeout angular?

Yes, that is perfectly fine to do.

How do you call a function after 2 seconds TypeScript?

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.


1 Answers

 private authenticate_loop() {
    setInterval (() => {
      console.log("Hello from setInterval");
    }, 500)
 }

setTimeout will run just one time, unless you create another setTimeout.

like image 186
dlcardozo Avatar answered Sep 22 '22 02:09

dlcardozo