7

I would like to call function from setInterval(). Here is the idea:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor(element: HTMLElement) {
        this.element = element;
        this.element.innerHTML += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
        //this.element.style.cssText = "-webkit-transform:rotate(7deg)";     
        //this.element.style.transition = "-webkit-transform: rotate(180deg)";         
    }

    start() {
        this.timerToken = setInterval(this.runningLoop(this.element), 500);        
    }

    stop() {
        clearTimeout(this.timerToken);
    }

    runningLoop(element: HTMLElement) {
        this.element.style.cssText = "-webkit-transform:rotate(7deg)";         
    }


}

window.onload = () => {
    var el = document.getElementById('content');
    var greeter = new Greeter(el);

    greeter.start();
};        

In this case i getting an exception:

Unhandled exception at line 13, column 9. Microsoft JScript runtime error: Invalid argument.

So i tried as following :

this.timerToken = setInterval(function () { this.runningLoop(this.element) }.bind, 500);

No exception but nothing happens..

Any ideas ?

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
Jviaches
  • 826
  • 3
  • 14
  • 30

2 Answers2

21
setInterval(this.runningLoop(this.element), 500);

The above invokes this.runningLoop before passing it to setInterval, setInterval is expecting a function but is receiving undefined. Wrap the call in an arrow function...

setInterval(() => this.runningLoop(this.element), 500);

And since you're not using the element argument in runningLoop, you can remove the argument and pass the method to setInterval...

setInterval(this.runningLoop, 500);
Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
1

This will be looping in the time that you want: setInterval(() => function(), time in miliseconds);

Now, if you want to stop whenever! Write a var before the interval: Declare on the top of your TS file: varInterval: any; this.varInterval = setInterval(() => function(), time in miliseconds);

You can call the method to stop like this: clearInterval(this.varInterval);

This work for me!

Carlos Galeano
  • 384
  • 5
  • 13