简体   繁体   English

Javascript闭包函数不返回正确的值

[英]Javascript closure function doesn't return the right value

I have a problem with my Javascript code and don't know why it doesn't run. 我的Javascript代码有问题,不知道它为什么不运行。

This is my timer: 这是我的计时器:

var time = 0;
startTimer();

function startTimer(){
    setInterval(function(){
    time=time+1;
    },10);
}

This code here works (I run timeoutTester() while clicking on a button, then it alerts and shows me the time difference): 这段代码可行(我在点击按钮时运行timeoutTester(),然后它会发出警报并显示时差):

function timeoutTester(){
    var snap_time1 = time;
    setTimeout(function(){
        var snap_time2 = time;
        var diff = snap_time2-snap_time1;
        alert(diff);            //works: ~100 everytime...
    },1000);
}

But this code here doesn't work (I run testTimer() by clicking on a button): 但是这里的代码不起作用(我通过单击按钮运行testTimer()):

function timeoutTester(){
    var snap_time1 = time;
    var result;
    setTimeout(function(){
        var snap_time2 = time;
        result = snap_time2-snap_time1;
    },1000);
    alert(result); //doesn't work! It always shows me: "undefined"
    return result;
}

function testTimer(){
    var counter = 0;
    setInterval(function(){
        counter = counter + 1;
        alert(counter);         //works: 1,2,3,....
        var result = timeoutTester();
        alert(result);  //doesn't work! It always shows me: "undefined"
    }, 3000);
}

Do you know where the problem might be? 你知道问题出在哪里吗? (No error while debugging in browser!) (在浏览器中调试时没有错误!)

UPDATE : 更新

I learned that alert(result); 我学会了警报(结果); is executed immediately, while result has no value yet. 立即执行,而结果尚无价值。

But since I'm calling timeoutTester() from the outside, I still need a return value from this function! 但是因为我从外部调用timeoutTester(),所以我仍然需要这个函数的返回值!

Any ideas? 有任何想法吗?

In your last example (the one that doesn't work), calling setTimeout(function()...) does not execute the function immediately, but does return immediately. 在你的最后一个例子中(那个不起作用的例子),调用setTimeout(function()...)不会立即执行该函数,但会立即返回。 When it returns, result is still undefined because the function has not yet executed. 返回时, result仍未定义,因为该函数尚未执行。

By the same token, the previous example (that has the call to alert() inside the timeout function) works because the call to alert() happens after result is assigned a value. 同样的道理,在前面的例子(具有呼叫alert()的超时函数内)的作品,因为呼叫alert()后发生的result被分配一个值。

If for whatever reason you don't want to call alert() directly from within the timeout function, you could rewrite the last example as: 如果由于某种原因您不想直接从超时函数中调用alert() ,您可以将最后一个示例重写为:

function timeoutTester(){
    var snap_time1 = time;
    setTimeout(function(){
        var snap_time2 = time;
        alertResult(snap_time2-snap_time1);
    },1000);
}
function alertResult(result) {
    alert(result);
}

(By the way, the call startTimer(1000000000000); looked scary until I realized that the argument was being ignored. :-).) (顺便说一下,调用startTimer(1000000000000);看起来很可怕,直到我意识到这个参数被忽略了。:-)。)

To get this done, you need to use a global: 要完成这项工作,您需要使用全局:

var timeoutTesterResult;

function timeoutTester(){
    var snap_time1 = time;
    var result;
    setTimeout(function(){
        var snap_time2 = time;
        timeoutTesterResult = snap_time2-snap_time1;
        alert(timeoutTesterResult);                    //works: ~100
    },1000);
}

And a second timeout who gets this global only after it's set/changed: 并且第二次超时只有在设置/更改后才会获得全局:

function testTimer(){
    var counter = 0;
    setInterval(function(){
        counter = counter + 1;
        alert(counter);         //works: 1,2,3,....
        timeoutTester();
        setTimeout("alert(timeoutTesterResult)",1000); //works: ~100
    }, 3000);
}

That's the "via global"-solution. 这就是“通过全球化”解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM