Reputation: 41
I want to use the timeOut function in jquery two times inside one function such as:
$('.button').click(function() {
setTimeout(function(){
Do something
},10000);
setTimeout(function(){
Do something
},10000);
});
Here is a sample of my code: https://jsfiddle.net/Ln74dLp2/3/
How can I chain the two timeouts after each other, instead of them running in parallel?
Upvotes: 0
Views: 348
Reputation: 107606
I'm thinking you have something misconfigured. Your code works just fine (though I dropped the timeout down to 1 second for the demo):
$('#one').hide();
$('#two').hide();
$('.button').click(function() {
setTimeout(function() {
$('#one').show();
setTimeout(function() {
$('#two').show();
}, 1000);
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="one">
Here is the first sentence
</p>
<p id="two">
Here is the second sentence
</p>
</div>
<button class="button">
click
</button>
A second option, which is probably overkill, but if you end up with a lot of these elements, you could use a single function that iterates over all the elements delaying each one by a multiple of 5 seconds:
$('#one').hide();
$('#two').hide();
$('.button').click(function() {
$('#one, #two').each(function(index) {
$(this).delay(5000 * (index + 1)).queue(function() { $(this).show(); });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="one">
Here is the first sentence
</p>
<p id="two">
Here is the second sentence
</p>
</div>
<button class="button">
click
</button>
Upvotes: 1
Reputation: 56
If you want for the first function to execute before second gets executed, do this
$('.button').click(function() {
setTimeout(function(){
Do something
setTimeout(function(){
Do something
},10000);
},10000);
});
Upvotes: 1