Jarla Jarla - 6 months ago 8
Javascript Question

How can I make multiple timeouts behind one another?

I want to show three messages behind one another always with 1 sec delay:

request.upload.addEventListener('progress',function(e){
setTimeout(function() {
$form.find('.progress-bar').width(percent+'%').html("first message");
}, 1000);
setTimeout(function() {
$form.find('.progress-bar').width(percent+'%').html("second message");
}, 1000);
setTimeout(function() {
$form.find('.progress-bar').width(percent+'%').html("third message");
}, 1000);
}


But I on my screen it displays only "third message".

Answer

Just use longer delays on the second two, perhaps 1000, 2000, and then 3000.

Example:

var $form = $("form");
$("input").on("click", function(e){
    var percent = 50; // dummy var
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("first message");
    }, 1000);
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("second message");
    }, 2000);
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("third message");
    }, 3000);
});
.progress-bar {
  display: inline-block;
}
<input type="button" value="Click Me">
<form>
  <div class="progress-bar"></div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

That said, whenver you find yourself repeating the exact same code with just a small variation, it's an opportunity to refactor. For instance:

["first message", "second message", "third message"].forEach(function(msg, index) {
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html(msg);
    }, 1000 * (index + 1));
});

Note we're using the index (0, 1, 2) plus one to multiply the timeout, so they appear successively.

Example:

var $form = $("form");
$("input").on("click", function(e){
    var percent = 50; // dummy var
    ["first message", "second message", "third message"].forEach(function(msg, index) {
        setTimeout(function() {
            $form.find('.progress-bar').width(percent+'%').html(msg);
        }, 1000 * (index + 1));
    });
});
.progress-bar {
  display: inline-block;
}
<input type="button" value="Click Me">
<form>
  <div class="progress-bar"></div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>