我有一組單詞,我的目標是每隔幾秒鐘在 HTML 模板中顯示每個單詞。結果應該是這樣的:https ://bootstrapmade.com/demo/iPortfolio/
我知道可以通過使用以下 JavaScript 代碼來做到這一點:
const typed = select('.typed')
if (typed) {
let typed_strings = typed.getAttribute('data-typed-items')
typed_strings = typed_strings.split(',')
new Typed('.typed', {
strings: typed_strings,
loop: true,
typeSpeed: 100,
backSpeed: 50,
backDelay: 2000
});
}
我嘗試使用打字稿復制相同的效果,而是撰寫了以下代碼:
export class HeroComponent implements OnInit {
words: string[] = ['marco', 'polo'];
word: string = "";
constructor() { }
ngOnInit(): void {
setTimeout(() => {
while(true){
for (let i=0; i < this.words.length; i ) {
setTimeout(() => {
this.word = this.words[i];
console.log(this.word)
}, 4000)
};
}}, 4000);
}
}
但是,一旦我運行該網站,它就會說它記憶體不足。
您能否建議一種聰明而優雅的方式來實作上面網站中鏈接的效果?
uj5u.com熱心網友回復:
洗掉使用for,while回圈和setTimeout
使用普通的 JavaScript setInterval,或者因為您使用的是 Angular,所以使用RxJS interval. 跟蹤一個index值(一個數字),使用它訪問陣列值 ( ),并在每次執行間隔時words[index]遞增index
您還可以添加一個if警衛來檢查陣列長度是否超過 - 如果超過則取消間隔
uj5u.com熱心網友回復:
words: string[] = ['marco', 'polo'];
word = new Subject<string>();
ngOnInit(): void {
for (let i = 0; i < this.words.length; i ) {
SetTimeout(() => this.word.next(this.words[i]), 4000)
}
}
你也可以試試:
words: string[] = ['marco', 'polo'];
word = new Subject<string>();
ngOnInit(): void {
of(...this.words)
.pipe(delay(4000))
.subscribe(this.word.next);
}
抱歉,如果某些解決方案有誤或無濟于事,我正在用手機寫信,目前無法驗證。
uj5u.com熱心網友回復:
這將是這樣做的方法:
export class OneComponent implements OnInit {
words = ['marco', 'polo'];
word = new Observable<string>();
ngOnInit(): void {
this.word = interval(4000).pipe(
map((num) => {
const index = num % this.words.length;
const word = this.words[index];
console.log(word);
return word;
})
);
}
}
然后在html中使用異步管道:
<p>{{ word | async }}</p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/464291.html
標籤:javascript 有角度的 打字稿 while循环 组件
