Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使函数调用顺序化?_Javascript - Fatal编程技术网

Javascript 如何使函数调用顺序化?

Javascript 如何使函数调用顺序化?,javascript,Javascript,我的代码调用一个函数的次数是特定的,该次数基于循环通过的数组的当前项,该项是一个数字。因此,如果数组的第一项是9,则函数被调用9次,之后,无论下一项是什么数字,都将是函数被再次调用的次数 根据数组中的数字,每组呼叫之间也会有一个暂停。因此,一旦调用函数的次数达到第一个数组项用数字指定的次数,就会出现暂停,并且再次调用函数的次数达到数组中第二个数组项用数字指定的次数 为了更好地理解,下面的代码调用名为“thefunction”的函数8次,然后暂停,然后调用它2次,然后暂停,然后15次。这是数组:v

我的代码调用一个函数的次数是特定的,该次数基于循环通过的数组的当前项,该项是一个数字。因此,如果数组的第一项是9,则函数被调用9次,之后,无论下一项是什么数字,都将是函数被再次调用的次数

根据数组中的数字,每组呼叫之间也会有一个暂停。因此,一旦调用函数的次数达到第一个数组项用数字指定的次数,就会出现暂停,并且再次调用函数的次数达到数组中第二个数组项用数字指定的次数

为了更好地理解,下面的代码调用名为“thefunction”的函数8次,然后暂停,然后调用它2次,然后暂停,然后15次。这是数组:var theArray=['8','2','15'];下面的代码遍历数组的每个项,并使用每个数组项(一个数字)来确定调用“thefunction”函数的次数。这是我的问题,当函数“thefunction”被多次调用时,我没有让代码正确执行

我认为这是因为对“thefunction”的调用不是顺序的。如何修改下面的代码,使其在调用“thefunction”一段时间后,调用是连续的,换句话说,函数将在再次调用之前完成。这样,如果数组中的第一个项是数字8,例如,“thefunction”将被调用8次,但实际上每次都能够在转到数组中的下一个数字项之前完全执行代码

 function runArray(arr, fn) {
 // initialize array index - can't use for loop here with async
 var index = 0;

 function next() {
 var cnt = +arr[index];
 for (var i = 0; i < cnt; i++) {
 fn(index, cnt);
 }
 // increment array index and see if there's more to do
 ++index;
 if (index < arr.length) {
       setTimeout(next, 400);
 }
}
// start the whole process if the array isn't empty
if (arr.length) {
   next();
}
}

var theArray = ['8','2','15'];
runArray(theArray, thefunction); //I'm calling the function called "thefunction" here
function thefunction(){
//my code. it doesn't get executed because calls aren't sequential I think
}
函数runArray(arr,fn){
//初始化数组索引-不能用于异步的循环
var指数=0;
函数next(){
var cnt=+arr[指数];
对于(变量i=0;i
队列是否适合解决此问题?您可以将代码分为两部分:一部分向队列添加函数,另一部分定期检查队列。如果上面有什么东西,它就会调用这个函数。此示例并不是对您的情况的精确映射,但它应该演示以下方法:

var queue = [];

// Enqueue a function.
function addFunctionToQueue() { 
    var func = function() { console.log("I'm a queued function"); };
    queue.push(func);
}

// Check the queue for a function, and run it if found. 
function runQueue() { 
    var fn;
    while (fn = queue.shift()) { // [].shift() is undefined, and undefined is falsey
        fn();
    }
    console.log("No more work to do, runQueue() ending.");
}

// Enqueue a function every second, and check the queue every 500ms
setInterval(addFunctionToQueue, 1000);
setInterval(runQueue, 500);

如果生成一个函数,该函数运行传入函数
n次
并将该函数添加到队列中,则可以确保函数将按照您将其排队的顺序运行

你听说过段落吗?使读取8个调用、2个调用和15个调用更容易,您的问题可能是由其他原因引起的。这些调用确实是顺序的,但是如果函数包含异步调用,则它们当然不会按顺序执行。因此,这完全取决于函数的内容。