异步函数的setTimeout [英] setTimeout on Asynchronous function

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

问题描述

我有一个异步函数,我希望在被触发之前有5000ms的延迟。我试图使用 setTimeout()来实现这一目标。这个异步函数发生在一个运行多次的循环中,异步函数每次传递不同的数据,因此 setInterval()不能在这里使用。

I have a asynchronous function that I want to have a 5000ms delay before being fired. I am trying to use setTimeout() to achieve this. This async function occurs in a loop that runs several times, with the async function being passed different data each time, thus setInterval() cannot be used here.

问题:异步功能立即被触发而没有延迟(控制台立即打印5 完成消息和循环没有任何延迟。发生了什么,我该如何解决?

Problem: The async function gets triggered instantly without delay (console prints 5 Done messages instantly` and loops without any delay. What happened, and how can I solve it?

Javascript代码

someFunction(listings, function() {
    for (var i in listings ) {
        var listing = listings[i];
        setTimeout(asyncFunction(listing, function(data) {
            console.log('Done');
        }), 5000);
    }
});


推荐答案

你必须将该函数包装在另一个函数中。目前,你正在调用函数,并将返回值作为参数传递给 setTimeout 。下面的代码将是(c (直接)将函数传递给 setTimeout 。 5秒后,该函数执行。

You have to wrap the function in another function. Currently, you're invoking the function, and passing the return value as an argument to setTimeout. The code below will (correctly) pass a function to setTimeout. After 5 seconds, the function executes.

由于存在范围问题,我不得不添加两个函数来实现所需的行为。 5秒后,循环已经完成,列表变量将等于 listing 中的最后一个元素。

I had to add two functions to achieve the desired behaviour, because of scoping issues. After 5 seconds, the loop has already finished, and the listing variable would be equal to the last element in listings.

someFunction(listings, function() {
    var counter = 0;  // Define counter for 5 second-delays between each call
    for (var i in listings ) {
        var listing = listings[i];
        (function(listing){ //Closure function
            setTimeout(function(){ //setTimeout function
                // Because of the closure, `listing` is unique
                asyncFunction(listing, function(a, b) {
                    console.log('Done');
                });
            }, 5000 * ++counter); //Increase counter for each loop
        })(listing);
    }
});

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

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