我想在一个函数中使用 jquery 中的 timeOut 函数两次,例如:
$('.button').click(function() {
setTimeout(function(){
Do something
},10000);
setTimeout(function(){
Do something
},10000);
});
这是我的代码示例:https://jsfiddle.net/Ln74dLp2/3/
如何将两个超时链接在一起,而不是并行运行?
最佳答案
我认为您配置有误。您的代码运行得很好(尽管我将演示的超时时间降低到 1 秒):
$('#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>
第二种选择,这可能有点过分了,但如果你最终得到很多这样的元素,你可以使用一个函数来迭代所有元素,将每个元素延迟 5 秒的倍数:
$('#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>
关于javascript - 如何在彼此之后而不是并行运行javascript超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36364085/