我想从 setInterval() 调用函数。这是想法:
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();
};
在这种情况下我得到一个异常(exception):
Unhandled exception at line 13, column 9. Microsoft JScript runtime error: Invalid argument.
所以我尝试如下:
this.timerToken = setInterval(function () { this.runningLoop(this.element) }.bind, 500);
没有异常(exception),但什么也没发生..
有什么想法吗?
最佳答案
setInterval(this.runningLoop(this.element), 500);
上面调用 this.runningLoop
在将其传递给 setInterval
之前,setInterval
需要一个函数但正在接收 undefined
。将调用包装在箭头函数中...
setInterval(() => this.runningLoop(this.element), 500);
并且由于您没有在 runningLoop
中使用元素参数,您可以删除该参数并将方法传递给 setInterval
...
setInterval(this.runningLoop, 500);
关于typescript - 调用方法表单 setInterval() 导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477246/