循环中创建的所有计时器(使用setTimeout)同时触发? [英] All timers created in loop (with setTimeout) fire at same time?

查看:267
本文介绍了循环中创建的所有计时器(使用setTimeout)同时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么我不能在每次请求之间得到所需的延迟吗?

它们都是一次性发生的。

Can someone explain why i cant get the desired delay between each request?
They are all happening at once.

$(window).load(function(){
    $('a[href]').each(function(){
        var linkk = $(this)
        var linkkhref = linkk.attr('href');

        window.setTimeout(function(){ conectar('HEAD', linkkhref, resp) }, 2000)

        function conectar(metodo, endereco, resposta, corpo) {
            callback = function(xhr) { resposta(xhr) };
            GM_xmlhttpRequest({
                "method"  : metodo,
                "url"     : endereco,
                "onerror" : callback,
                "onload"  : callback,
                "headers" : {'Content-Type':'application/x-www-form-urlencoded'},
                "data"    : corpo
            });
        };

        function resp(responseDetails) {
            // my response code here
        };
    });
});

我知道我使用Greasemonkey特定功能,但问题是关于javascript。

不需要转基因知识。 :)

I know im using a Greasemonkey specific function, but the question is about javascript.
No GM knowledge required. :)

推荐答案

循环立即运行并延迟每次执行 conectar 从时间码开始的2000ms的功能。

The loop is run just instantly and delay every execution of conectar function for 2000ms from the time code is exectued.

对于简单的情况我会使用:

For simple case I'd use:

$('a[href]').each(function(idx){
    ...
    window.setTimeout(function(){ conectar('HEAD', linkkhref, resp) }, idx*2000)

这篇关于循环中创建的所有计时器(使用setTimeout)同时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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