Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 调用方法form setInterval(),导致异常_Typescript_This - Fatal编程技术网

Typescript 调用方法form setInterval(),导致异常

Typescript 调用方法form setInterval(),导致异常,typescript,this,Typescript,This,我想从setInterval()调用函数。以下是想法: class Greeter { element: HTMLElement; span: HTMLElement; timerToken: number; constructor(element: HTMLElement) { this.element = element; this.element.innerHTML += "The time is: "; t

我想从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();
};        
在这种情况下,我得到一个异常:

第13行第9列的未处理异常。Microsoft JScript运行时错误:参数无效

因此,我尝试如下:

this.timerToken = setInterval(function () { this.runningLoop(this.element) }.bind, 500);
没有例外,但什么也没有发生

有什么想法吗

setInterval(this.runningLoop(this.element), 500);
上面调用了
this.runningLoop
,然后将其传递给
setInterval
setInterval
需要一个函数,但正在接收
未定义的
。将调用包装在箭头函数中

setInterval(() => this.runningLoop(this.element), 500);
由于您没有在
runningLoop
中使用元素参数,因此可以删除该参数并将该方法传递给
setInterval

setInterval(this.runningLoop, 500);

这将在您想要的时间内循环: setInterval(()=>function(),时间单位为毫秒)

现在,如果你想随时停下来!在间隔之前写入变量: 在TS文件顶部声明: 变量区间:任何; this.varInterval=setInterval(()=>function(),时间单位为毫秒)

您可以按如下方式调用该方法以停止: clearInterval(这是VariInterval)


这是我的工作

如何取消它?@crh225将setInterval分配给一个变量。然后是window.clearInterval(variableName);设置间隔停止解决方案链接: