问题描述
我想在每次间隔调用之间实现间隙/延迟, 我在下面尝试过,但似乎不起作用。
pollOnInterval(threshold = 4000): Observable<any> {
let thresholdValue = threshold;
const increaseBy = 2000;
const maxCount = 10;
return interval(thresholdValue).pipe(take(maxCount)).pipe(delay(increaseBy)).pipe(map(() => {
thresholdValue = thresholdValue + increaseBy;
console.log((new Date).toLocaleTimeString());
}));
}
输出
下午 2:34:21
下午 2:34:25
下午 2:34:29
下午 2:34:33
下午 2:34:37
下午 2:34:41
下午 2:34:45
下午 2:34:49
下午 2:34:53
下午 2:34:57
Edit -1 我试过 debounce 和 debouceTime,也没有用, Stackbliz 链接:https://stackblitz.com/edit/angular-ivy-tinm4r?file=src%2Fapp%2Fapp.component.ts
编辑 - 2我需要以下方式
下午 2:34:21
下午 2:34:27
下午 2:34:35
解决方法
-
您可以在单个
pipe()
中管道化所有运算符。每个操作员不需要自己的管道。 -
正如我在评论中提到的,一旦使用
interval()
触发thresholdValue
,对thresholdValue
变量的后续更改不会对 {{ 1}} 函数。它将在interval()
initally 表示的每个时间间隔内继续发射。 -
目前 observable 正在发射
thresholdValue
,因为undefined
没有返回任何内容。 -
您需要使用
map
并将延迟单独传送到每个发射。如果没有,concatMap
将作为一个整体通过管道传输到delay
,如问题所示。
试试下面的方法
interval
var { from,of,Observable,interval } = rxjs;
var { tap,delay,take,map,concatMap } = rxjs.operators;
var displayBox = document.getElementById('display');
function pollOnInterval(threshold = 4000) {
let increaseBy = 4000; // delay for first emission from `interval`
const maxCount = 10;
return interval(4000).pipe(
concatMap(value => of(value).pipe(
tap(() =>
displayBox.innerHTML += `
Interval: ${new Date().toLocaleTimeString()};
Delay: ${increaseBy/1000}s
<br />
`
),delay(increaseBy)
)),tap(() => increaseBy += 2000),// <-- adjust `increaseBy`
take(maxCount),map(() => new Date().toLocaleTimeString())
);
}
pollOnInterval().subscribe({
next: value => displayBox.innerHTML += `Subscription: ${value}<br /><hr>`,error: null,complete: () => displayBox.innerHTML += 'Observable complete.'
});