leonking93
leonking93

Reputation: 39

How to change innerHTML every few seconds

I am learning Javascript and I want to loop through text in a span on my webpage. I had done this with CSS, but it was not supported on Safari browser, so I thought I'd take a different approach and use Javascript. I would like for the text to loop through the 3 strings that I have, every 2 seconds, and do it indefinitely. Whenever I try to use a while loop, the page just never loads.

    const title = document.getElementById('job-title');
    let loop = true;
    while (loop = true) {
        title.innerHTML = "Web Developer";
        setTimeout(function(){ title.innerHTML = "Web Designer" }, 2000);
        setTimeout(function(){ title.innerHTML = "Graphic Designer" }, 4000);
        ; 
    }
  } ```

Upvotes: 1

Views: 2901

Answers (4)

Sean
Sean

Reputation: 827

This can be done through setTimeouts brother setInterval which does the function every n milliseconds. I also suggest you use .textContent opposed to .innerHTML if youre not setting any HTML

var i = 1; 
const title = document.getElementById("job-title");
var texts = [
    "Web Designer",
    "Graphic Designer"
];

title.textContent = texts[0];

var loop = setInterval(function() {
    title.textContent = texts[i];
    i = (i+1) % texts.length; // Allows the array to loop
}, 2000);

Upvotes: 0

Jin Tan
Jin Tan

Reputation: 608

Your javascript is running forever so your page never load.

Your description makes me think that you want to build a slideshow. If that is the case, you should refer to this: Learn how to create a responsive slideshow with CSS and JavaScript.

Upvotes: -1

SoluableNonagon
SoluableNonagon

Reputation: 11755

A while loop that is always true just ties up the thread on your page; you need to tell it to wait and try again later.

Recursion will create a stack but achieves your goal. Used setTimeout but the setInterval approach is probably a better way to go.

const title = document.getElementById('title');

let text = 'Web Developer';

function doThing() {
  if (text === 'Web Developer'){
    text = 'Designer';
  } else {
    text = 'Web Developer';
  }
  title.innerHTML = text;

  setTimeout(doThing, 2000)
}
doThing();
<div id='title'>Web Developer</div>

Upvotes: -1

Charlie
Charlie

Reputation: 23798

What you need is only a timer - that is setInterval

let titles = ['Web Developer', 'Web Designer', 'Graphic Designer'];
let currentIndex = 0;
let aSpan = document.getElementById('job-title');

setInterval(() => {
   
   aSpan.innerHTML= titles[currentIndex];   
   
   currentIndex++;
   
   if (currentIndex === 3)
    currentIndex = 0;

}, 1000)
<span id="job-title"></span>

Upvotes: 4

Related Questions