Hetrogon
Hetrogon

Reputation: 11

How to rotate from different titles

No, I am not talking about <h1> or something like that. I am talking about the <title> element. I created a function, that delays every .5 seconds or so, and changes titles.

The script I have developed reads the array, which includes the titles, and rotates from it. The first time I have ran it, I did not use setTimeout, and it ran instantly, I couldnt read anything.

But when I tried using the setTimeout function, it started to return undefined. What is the problem with this code?

for(var i = 0; i < titles.length ; i++){
              setTimeout(function () {document.title = titles[i]}, 500)
}

Upvotes: 0

Views: 35

Answers (1)

Kinglish
Kinglish

Reputation: 23664

You're going about this the wrong way (IMO). Using a loop you'll fire off all your timeouts at once. You'd be better off using setInterval

let i = 0, titles = ['title1', 'title2', 'title3'];
let int = setInterval(() => {
  document.title = titles[i];
  console.log('doc.title: ', document.title);
  if (i++ >= titles.length - 1) clearInterval(int);
}, 500)

Upvotes: 1

Related Questions