Reeseman
Reeseman

Reputation: 1

Timing in JavaScript: Finding a way to make setInterval alternate time

I am building a web page for a class project, and specifically, an "about us" page that iterates through pictures and descriptions of the team members. On the view, I have this:

setInterval(function() {
  $("#about-img").attr('src', img_src[i]);
  $("#name").html(names[i]);
  $("#description").html(descriptions[i]);
  i = (i + 1) % img_src.length;
}, 8000);

This effectively iterates, however, sometimes descriptions are longer than others. Is there any way to wait longer, the longer the description is? Something simple would be

waits(descriptions[i].length * 50);

Right in the setInterval function, but javascript has no way of doing that. What can I do? setTimeout is asynchronous, and I cannot influence the second parameter of setInterval from the scope of the first.

Upvotes: 0

Views: 71

Answers (2)

www139
www139

Reputation: 5227

This is how you might do the timer(s) involved:

To do it just once after some time:

window.setTimeout(function(){alert('test');}, 3000);//3 seconds

Do it forever:

window.setInterval(function(alert('test');){}, 3000);//do it forever in 3 second intervals

Upvotes: 0

epascarello
epascarello

Reputation: 207531

Use setTimeout instead of an interval

function changeMessage () {
    $("#about-img").attr('src', img_src[i]);
    $("#name").html(names[i]);
    $("#description").html(descriptions[i]);
    i = (i + 1) % img_src.length;
    window.setTimeout(changeMessage, descriptions[i].length * 50);
}

Upvotes: 3

Related Questions