Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  22] [ 1]  / answers: 1 / hits: 18514  / 6 Years ago, sun, march 4, 2018, 12:00:00

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();

More From » typescript

 Answers
7

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);

[#55022] Wednesday, February 28, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monica

Total Points: 308
Total Questions: 102
Total Answers: 109

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;