简体   繁体   中英

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);
        ; 
    }
  } ```

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>

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>

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.

This can be done through setTimeout s 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM