javascript - 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) 中,输出是相同的,因此是直觉。好吧,我宁愿研究“这个”。谢谢大家的回答和评论。非常感激。
解决方案
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);
推荐阅读
- c - 升级到 Catalina 10.15 后无法在 Mac 上编译 C 程序
- regex - 在 CSV 数据集的每个字母之间插入的替换字符。如何更换?
- python - 是否有一个 pandas 函数可以对数据框中的一组先前行元素求和?
- html - 为什么 Vuetify 表格显示不一致的单元格宽度?
- c# - 如何从 XSD 获取所有节点?
- android - 如何以编程方式并排放置不同大小的按钮?
- sql-server - BCP 为有效日期格式抛出“无效字符值”?
- sql - 尝试使用 Databricks 和 SQL 创建表并将数据加载到同一个表中
- python - 如何修复对 Twilio 的 python POST 请求上的“不支持的媒体类型”错误
- android - 替换后如何回到第一个Android Fragment