Make <p> disappear after certain amount of time using JS or JQuery

Viewed 344

I'm working on a project that requires me to show and hide text. I want one verse to appear on the screen, disappear after x amount of time, and then new text appears. I'm pretty new to Javascript & JQuery so I'm not really sure how to make this work. Below is the code I have so far:

HTML

<p class="mast__text js-spanize" id="verse1">
 Magnetic light in the blue-high haze
</p>

<p class="mast__text js-spanize" id="verse2">
 A magnifying glass upon my face
</p>

<p class="mast__text js-spanize" id="verse3">
 It's so hot I've been melting out here 
</p>

JS:

$("#verse1").show();
setTimeout(function() { $("#verse1").hide(); }, 2000);

$("#verse2").show();
setTimeout(function() { $("#verse2").hide(); }, 2000);

$("#verse3").show();
setTimeout(function() { $("#verse3").hide(); }, 2000);

Both functions seem to be called at the same time which is making the text appear and disappear at the same time. I'm sure that there is an easy fix to this that I'm overlooking, but I've looked online and can't seem to figure this out.

1 Answers

The issue is that the code assumes that the setTimeout function waits for the time to finish. Instead, the code continues on, an makes note to run the code after a specified time. To fix it, you simply need to nest the setTimeout functions:

$("#verse2").hide(); // So these aren't showing at the start
$("#verse3").hide();

$("#verse1").show();
setTimeout(function() {
    $("#verse1").hide();

    $("#verse2").show();
    setTimeout(function() {
        $("#verse2").hide();

        $("#verse3").show();
        setTimeout(function() { $("#verse3").hide(); }, 2000);
    }, 2000);

}, 2000);
Related