JavaScript的睡觉的setTimeout [英] javascript sleep with SetTimeout

查看:92
本文介绍了JavaScript的睡觉的setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送电子邮件以10秒延时之间。我写这篇code:

I'm trying to send emails with a 10 seconds delay between. I wrote this code:

$(document).ready(function() {
    for (i = 0; i < 20; i++) {
        setTimeout("SendEmail(" + i + ")", 5000);
    }
});

function SendEmail(id) {
    $.get("mimesender.php?id=" + id, function(data) {
        var toAppend = "<span>     " + data + "</span>"
        $("#sentTo").append(toAppend);
    });
}

服务器端code(PHP)获取ID并从数据库中选择与指定标识的电子邮件

server side code(php) gets the id and selects the email with the specified id from the database

$query="select email from clienti where id =".$id;

然后发送电子邮件,并发送回当前电子邮件

then sends the email, and sends back the current email

echo email;

然而,什么是错在这里。这似乎是函数等待5秒钟,JS,再一次显示所有的20个电子邮件地址。

However, something is wrong here. It seems like the the js function waits for 5 seconds, and then displays all the 20 email addresses at once.

你能告诉我什么,我做错了吗?任何休眠的解决方法将大大AP preciated:)

Can you tell me what I'm doing wrong ? any "sleep "workaround will be greatly appreciated :)

推荐答案

您应该创建一个功能5秒后自称

You should create a function which calls itself after 5 seconds

var i=0;

function sendEmailNow() {
     SendEmail(i);
     ++i;
   if(i<20) {
        setTimeout(sendEmailNow, 5000);
    }
}

这篇关于JavaScript的睡觉的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆