4

I am learning Typescript and am trying to print a console message a number of times over a period of time. But in my test this happens once, you know the reason?

The code is below:

 class Class {
    private msg: string;
    constructor(msg: string) {
        this.msg = msg;
    }
    private printMsg(): void {
        console.log(this.msg);
    };
    public repeatMsg(): void {
        let intervalo = setInterval(this.printMsg(), 2000);
        setTimeout(function() {
            clearInterval(intervalo);
        }, 40000);
    }
}

let test: Class;
test = new Class("Hello");
test.repeatMsg();
3
  • 4
    Remove the (), you're calling the function immediately, setInterval expects a function reference, like you provided via anonymous function in the timeout Commented Mar 4, 2018 at 3:05
  • 2
    Possible duplicate of Calling functions with setTimeout() Commented Mar 4, 2018 at 3:06
  • Removing () would break this.msg. Using this.pringMsg.bind(this) would work though. Commented Mar 4, 2018 at 3:14

1 Answer 1

15

The problem in your code is there:

setInterval(this.printMsg(), 2000);

setInterval accepts a function as a first parameter. Expression this.printMsg() is a call of the function, and is void actually. There are two ways to fix it. Use lambda:

setInterval(() = > this.printMsg(), 2000);

Or use bind:

setInterval(this.printMsg.bind(this), 2000);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.