取消定时器
setImmediate()
、setInterval()
和 setTimeout()
方法各自返回表示调度的定时器的对象。
这些可用于取消定时器并防止其触发。
对于 setImmediate()
和 setTimeout()
的 promise 化变体,可以使用 AbortController
来取消定时器。
当取消时,返回的 Promise 将使用 'AbortError'
拒绝。
对于 setImmediate()
:
const util = require('util');
const setImmediatePromise = util.promisify(setImmediate);
const ac = new AbortController();
const signal = ac.signal;
setImmediatePromise('foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.name === 'AbortError')
console.log('The immediate was aborted');
});
ac.abort();
对于 setTimeout()
:
const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);
const ac = new AbortController();
const signal = ac.signal;
setTimeoutPromise(1000, 'foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.name === 'AbortError')
console.log('The timeout was aborted');
});
ac.abort();
The setImmediate()
, setInterval()
, and setTimeout()
methods
each return objects that represent the scheduled timers. These can be used to
cancel the timer and prevent it from triggering.
For the promisified variants of setImmediate()
and setTimeout()
,
an AbortController
may be used to cancel the timer. When canceled, the
returned Promises will be rejected with an 'AbortError'
.
For setImmediate()
:
const util = require('util');
const setImmediatePromise = util.promisify(setImmediate);
const ac = new AbortController();
const signal = ac.signal;
setImmediatePromise('foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.name === 'AbortError')
console.log('The immediate was aborted');
});
ac.abort();
For setTimeout()
:
const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);
const ac = new AbortController();
const signal = ac.signal;
setTimeoutPromise(1000, 'foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.name === 'AbortError')
console.log('The timeout was aborted');
});
ac.abort();