The form of the setInterval () call method that throws an exception

I would like to call a function from setInterval (). Here is an 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 get an exception:

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

So, I tried the following:

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

No exceptions, but nothing happens.

Any ideas?

+4
source share
1 answer
setInterval(this.runningLoop(this.element), 500);

The above calls this.runningLoopbefore passing it to setInterval, setIntervalexpects a function, but receives undefined. Wrap the call with the arrow function ...

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

And since you are not using element's argument runningLoop, you can remove the argument and pass a method setInterval...

setInterval(this.runningLoop, 500);
+11

Source: https://habr.com/ru/post/1546479/


All Articles