首页 > 解决方案 > Nodejs:使用'this'的clearInterval()

问题描述

我想 clearInterval() ,我可以使用 clearInterval(myInterval) 这样做,但为什么我不能使用 clearInterval(this) ?

这是有效的代码:

var test =  setInterval(function(){
            request.post({url: myURL, form: {
                user : myUser,
                pass : myPass
                function(err,res,body){
                    if(res.statusCode === 302) clearInterval(test);
                })
        }, 1100)

这是不起作用的代码:

setInterval(function(){
            var that = this;
            request.post({url: myURL, form: {
                user : myUser,
                pass : myPass
                function(err,res,body){
                    if(res.statusCode === 302) clearInterval(that);
                })
        }, 1100)

编辑1:我很抱歉这个可怜的问题。我对“this”的概念不太熟悉,直觉上认为使用“this”我可以清除Interval()。原因是当我在 setInterval 函数内的第一个代码中的 console.log(test) 和第二个代码中的 console.log(this) 中,输出是相同的,因此是直觉。好吧,我宁愿研究“这个”。谢谢大家的回答和评论。非常感激。

标签: javascriptnode.jstimerclearinterval

解决方案


setInterval()的值中不提供 timerID this。你不能那样使用它。timerID 仅作为setInterval()第一个示例中的返回值提供。

您可以创建自己的小型计时器对象,以根据需要封装事物,并为您存储 timerID。

例如,您可以像这样创建自己的计时器对象,将计时器对象作为值this传递给回调。然后你可以this用来调用clearInterval()对象的方法。

class IntervalTimer() {
    start(cb, t) {
        // if there was a previous interval going here, stop it
        // only one per timer object permitted
        this.stop();
        this.id = setInterval(() => {
            cb.call(this);   // set the this value to be our object
        }, t);
    }
    stop() {
        if (this.id) {
            clearInterval(this.id);
            this.id = null;
        }
    }
}

// usage
let t = new IntervalTimer();
t.start(function() {
   // based on some logic, decide to clear the interval
   // the value of "this" has been set to the timer object
   this.stop();
}, 1000);

推荐阅读