javascript - 如何在彼此之后而不是并行运行javascript超时?

标签 javascript jquery

我想在一个函数中使用 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/

相关文章:

javascript - 获取单击按钮的值/属性作为 event.data,带有 .on ("click"...)

javascript - AJAX日历更新页面rails 4

jQuery - Shadowbox 重新绑定(bind)

javascript - 无法识别父字符串 JQuery 中的子字符串

javascript - D3 : Cannot append simple path to svg container

php - 从 php 到 javascript 传递顺序安全的值

javascript - 正则表达式仅数字,破折号是可选的

javascript - 如何准备这个遗留类以导入到 VueJs 应用程序?

javascript - jQuery - 删除列表中的项目

javascript - 如何检测文本区域中的前一行是否为空