【问题标题】:How to get two events to occur with delay between them如何让两个事件在它们之间发生延迟
【发布时间】:2015-12-17 15:52:01
【问题描述】:

所以,我将一些字符串加载到一个名为消息的数组中。我想在没有消息显示的半秒内循环浏览消息。我的代码应该这样做,但无论出于何种原因,它都没有。根本没有文字显示。

这是我的代码:

        function NextElement()
        {
            var x = messages.shift();
            messages.push(x);
            return x;
        }
        function doer()
        {
            $("p.message").text(NextElement());
        }
        function doer2()
        {
            $("p.message").text("");
        }
        $( document ).ready(function() 
        {
         setInterval( doer,1000);
         setTimeout(function() {}, 500);
         setInterval( doer2,1000);
        });

如果如果删除此行

       $("p.message").text("");

消息显示,但半秒后不消失。

我正在查看 this page 以了解超时的工作原理,也许我误解了。似乎它的工作方式与 Java/C# 中的 thread.sleep() 不同

【问题讨论】:

  • 展示你的html结构就好了
  • 2 个间隔计时器基本上同时启动和运行。因此,每条消息可能会在显示后立即被删除。
  • 为什么会这样?我以为这就是 setTimeout(function() {}, 500);正在注意将它们隔开。
  • html 结构是一个带有“消息”类的空 p 元素,我认为它不值得展示。
  • @AlexanderRyanBaggett 目前,超时是调用一个空函数,定时器不会自动堆叠,所以没有影响。要延迟它的开始,必须在提供给超时的function 内设置间隔——setTimeout(function () { setInterval(doer2, 1000); }, 500);

标签: javascript jquery google-chrome


【解决方案1】:

正如 @Jonathan Lonowski 在 cmets 中提到的,这两个区间基本上是同时运行的。

编辑

例子:

func1();
setTimeout(CODE, [DELAY]);
func2();

setTimeout 不会中断上述代码的同步流程。
无论[DELAY] 有多长,这两个函数(func1func2)都会流畅执行。
setTimeout 实际上延迟CODE


function NextElement(){
    var x = messages.shift();
    messages.push(x);
    return x;
}
function doer(){
    $("p.message").text(NextElement());
    setTimeout(doer2, 1000);
}
function doer2(){
    $("p.message").text("");
    setTimeout(doer, 500);
}

doer();

JSFiddle

【讨论】:

  • 你能解释一下为什么这个超时的使用是正确的,我的使用是不正确的吗?
【解决方案2】:

尝试使用.queue()

var messages = ["", "a", "", "b", "", "c", "", "d", "", "e", "", "f", "", "g"],
p = $("p.message");

(function cycle() {
  p.delay(500, "messages").queue("messages", $.map(messages, function(msg) {
    return function(next) {
      $(this).text(msg);
      setTimeout(next, 500)
    }
  })).dequeue("messages").promise("messages").then(cycle)
}())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<p class="message"></p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2020-08-10
    • 2017-08-06
    相关资源
    最近更新 更多