setTimeout函数发生了什么

What is happening to my setTimeout function?

本文关键字:什么 发生了 函数 setTimeout      更新时间:2023-09-26

我试图使一个函数(下一步),需要一个函数和等待时间作为其参数。然后,它将有一个计数器,该计数器将随着函数调用而增加。

var up = function() {
    var counter = 0;  
   return counter += 1;
};
var next = function(fn, wait) {
    var total = 0; //set total variable to 0
    var x = fn(); //call the function and set answer to a variable
    total+=x; //add the answer to the total
    var n = setTimeout(function(){fn();}, wait); 
//THIS BIT DOES NOT GIVE ME 1? Instead I get any number from 16 (depenging on how many times I call it! It increases as I keep calling the function....?!)
    total += n; 
    return total; 
};
next(up,1000);

我完全困惑为什么setTimeout是这样工作的?!

我已经环顾四周为这个问题的答案,并没有击中幸运-我很抱歉,如果我错过了这里的问题,如果它已经问过了!我确实遇到了这个问题,并尝试将变量计数器放在外面,但这似乎没有任何区别……

这个问题似乎更接近于我感到困惑的领域,但我并没有更接近于理解我的问题,对于为什么我得到的返回值比我期望的要高得多,任何帮助都会非常感激。

我尝试的另一种方法是:

var next = function(func, wait) {
    var storedAnswer = 0;
    var answer = function() {
        return storedAnswer;
    }
    var increase = func;
    setTimeout(increase, wait); 
    return answer();
};
next(up, 100);  // gives me 0...? the up function here is defined in the above code...

但这最终导致我没有得到任何移动的答案…

setTimeout返回超时id,而不是回调的返回值。

var timeoutID =窗口。setTimeout(代码,(延迟));

Try this:

setTimeout(function(){total += fn();}, wait);

setTimeout返回的值为int型。但它也是一个全局超时计数器。也就是说,每个超时都共享同一个计数器。所以你得到16只是意味着在某个地方,在你的页面的某个部分,其他15个超时已经执行。

在这种情况下,返回一个16或基本上不是1的整数是完全正常的,并且将该整数与clearTimeout一起使用,例如,仍然会正确引用所使用的超时。

除了

在node.js中(这看起来不像你正在使用的),机制是相同的,除了返回一个timeoutObject,它仍然可以用来清除超时。它还用于延续和其他服务器端相关的定时机制。

nsetTimeout的返回值,是一个数字标识符,可以传递给clearTimeout以取消超时。

这里的基本问题是setTimeout只是在给定延迟之后注册一个要调用的函数,然后立即继续执行到下一行。所以这一行:

total += n;

而不是等待超时完成。它会立即发生,而n,就像我说的,不是你想要的值。

你需要你的next函数接受一个回调,它可以在超时完成时调用。

var next = function(fn, wait, callback) {
    var total = 0;
    var x = fn();
    total+=x;
    setTimeout(function() {
        var n = fn();
        total += n;
        callback(total);
    }, wait); 
};

你可以这样称呼它:

next(up, 100, function(total) {
    // This function runs after the operation is done; do something with the total.
});