2 回答

TA贡献1834条经验 获得超8个赞
下面的流zip创建每 1000 毫秒向订阅的 lambda 发送一个对象。一旦不再有任何对象,它就会结束。
takeUntil是可用于控制流何时结束的更通用的运算符之一。在这种情况下,当cancel$发出一个值时,整个流就结束了。
const cancel$ = new Subject();
zip(
from(animations),
interval(1000)
).pipe(
takeUntil(cancel$),
map(([x,y]) => x)
).subscribe(animation => {
switch (animation.type) {
case "animation-type": {
//change the style of some elements
...
default:
break;
}
});
然后,如果您需要停止它,您可以运行此行
cancel$.next();
当然,您可以传入一个观察者对象,而不是使用 lambda 函数进行订阅。
).subscribe({
next: animation => {
switch (animation.type) {
case "animation-type": {
//change the style of some elements
...
default:
break;
}
},
complete: () => {
// Final touches/ reset the animation/ whatever
},
error: err => {
console.log("Got an error: " + err.message);
throw(err);
}
})

TA贡献1900条经验 获得超5个赞
您可以存储超时函数:
const timeouts = [];
animations.forEach((animation, index) => {
switch (animation.type) {
case "animation-type": {
timeouts[index] = setTimeout(() => {
//change the style of some elements
}, index * 1000);
break;
}
...
default:
break;
}
});
然后:
timeouts.map(timer=> clearTimeout(timer));
如果您正在使用 React 项目,则可以使用useRef钩子
const timeouts = useRef([]);
animations.forEach((animation, index) => {
switch (animation.type) {
case "animation-type": {
timeouts.current[index] = setTimeout(() => {
//change the style of some elements
}, index * 1000);
break;
}
...
default:
break;
}
});
并清除超时:
timeouts.current.map(timer=> clearTimeout(timer));
添加回答
举报