关键字'this'可以用来引用javascript中定时器内部的setInterval方法吗

我已经知道setIntervaljavascript中的函数每隔固定的时间重复执行一个函数或一段代码。我已经知道它的语法如下:

setInterval(func|code, [delay], [arg1], [arg2], ...)

我的问题是:我可以使用关键字“this”作为参数来引用计时器 ID(我的例子中的所有参数都作为外部回调函数的参数传递)?

提前致谢。


海绵宝宝撒
浏览 109回答 1
1回答

宝慕林4294392

在创建计时器之前,您不能直接传递计时器的 ID。问题是你必须调用&nbsp;setInterval才能获取 ID,然后才能将其实际传递给被调用的函数:let&nbsp;timerId&nbsp;=&nbsp;setInterval(function()&nbsp;{},&nbsp;1000,&nbsp;timerId);&nbsp; //error&nbsp;-&nbsp;we&nbsp;are&nbsp;using&nbsp;`timerId`&nbsp;before&nbsp;its&nbsp;declaration&nbsp;is&nbsp;finished传递一个对象但是,您可以利用对象在共享相同引用的情况下工作的方式。因此,您可以初始化一个对象,这意味着该变量存在,然后调用setInterval并将计时器ID记录为该对象的属性。然后将该对象作为参数传递给回调。当回调执行时,对象属性肯定会被填充,您可以只使用其中的值:let cb;{ //callback in one scope&nbsp;&nbsp;&nbsp; //simple counter that stops at zero&nbsp; let i = 3;&nbsp; cb = timerContext => {&nbsp; &nbsp; console.log(i--);&nbsp; &nbsp; if (i < 0) {&nbsp; &nbsp; &nbsp; console.log("finish");&nbsp; &nbsp; &nbsp; clearInterval(timerContext.timerId);&nbsp; &nbsp; }&nbsp; }}{//start the timer in a different scope&nbsp; let context = { timerId: null };&nbsp;&nbsp;&nbsp; context.timerId = setInterval(cb, 1000, context);}创建一个包装器或者,如果您在调用 setInterval 时为其创建包装函数,则只能向外部回调传递计时器 ID:let cb;{ //callback in one scope&nbsp;&nbsp;&nbsp; //simple counter that stops at zero&nbsp; let i = 3;&nbsp; cb = timerId => {&nbsp; &nbsp; console.log(i--);&nbsp; &nbsp; if (i < 0) {&nbsp; &nbsp; &nbsp; console.log("finish");&nbsp; &nbsp; &nbsp; clearInterval(timerId);&nbsp; &nbsp; }&nbsp; }}{//start the timer in a different scope&nbsp; let timerId = setInterval(() => cb(timerId), 1000);}传递为thisthis如果您愿意,如果您的回调是普通函数,则可以以任一方式将计时器 ID 作为上下文传递:目的let cb;{ //callback in one scope&nbsp;&nbsp;&nbsp; //simple counter that stops at zero&nbsp; let i = 3;&nbsp; cb = function() {&nbsp; &nbsp; console.log(i--);&nbsp; &nbsp; if (i < 0) {&nbsp; &nbsp; &nbsp; console.log("finish");&nbsp; &nbsp; &nbsp; clearInterval(this.timerId);&nbsp; &nbsp; }&nbsp; }}{//start the timer in a different scope&nbsp; let context = { timerId: null };&nbsp;&nbsp;&nbsp; context.timerId = setInterval(cb.bind(context), 1000);}只要身份证号let cb;{ //callback in one scope&nbsp;&nbsp;&nbsp; //simple counter that stops at zero&nbsp; let i = 3;&nbsp; cb = function() {&nbsp; &nbsp; console.log(i--);&nbsp; &nbsp; if (i < 0) {&nbsp; &nbsp; &nbsp; console.log("finish");&nbsp; &nbsp; &nbsp; clearInterval(this);&nbsp; &nbsp; }&nbsp; }}{//start the timer in a different scope&nbsp; let timerId = setInterval(() => cb.call(timerId), 1000);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript