妄徒之命 2016-05-23 21:27 采纳率: 100%
浏览 40

延迟jQuery不起作用

Hi guys I don't know why my timing function is not working. Consider the following code...

$( document ).ready(function() {
    $.ajax({
        type: 'GET',
        url: 'conversation.json',
        dataType: 'json',
        success: function (data) {
            var conversation = data.conversation1;
            $.each(conversation, function(i, user) {
                setTimeout(function () {
                    $('<li>').attr({
                        class : 'list-group-item',
                    }).text(user.nombre + " : " + user.text).
                    appendTo('#messages');
                }, 3000);
            });
        }
    });
});

I get a json by ajax and I want to show each message by creating time 1 or 2 seconds, it works but just the first time, but after that, all the messages appear at once.

If some one could help me please to understand whats is going on.

Thanks guys I will keep searching. :(

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-05-23 21:31
    关注

    Just multiply the timeout delay in your .each loop by the iteration count to have it appear as an incremented delay for each message. Observe the following...

    $.each(conversation, function(i, user) {
        setTimeout(function () {
            $('<li>').attr({
                class : 'list-group-item',
            })
            .text(user.nombre + " : " + user.text)
            .appendTo('#messages');
        }, 3000 * (i + 1)); // 3000, 6000, 9000 etc.
    });
    

    JSFiddle Link - simplified demo

    评论

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services