jQuery javascript setInterval() 和变量范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19123440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:13:47  来源:igfitidea点击:

javascript setInterval() and Variable Scope

javascriptjqueryvariablesglobal-variables

提问by Jaideep Singh

OK, I have read several questions here with the same title but still couldn't find a solution to my problem. I'm working on a basic javascript count down timer and I'm stuck on updating the value of the avariable.

好的,我在这里阅读了几个具有相同标题的问题,但仍然找不到解决我的问题的方法。我正在开发一个基本的 javascript 倒数计时器,但我一直在更新a变量的值。

a = 100;
var i = setInterval( function(){ timer( a ); }, 1000 );

function timer( a ){
    console.log( a );
    if( a < 1 ){     
        console.log( 'Reaching Stop' ); 
            clearInterval( i );
            return;         
    } 
    a -= 1;
}

As I'm decrementing the value of aby -1, console.log( a )should be 1 less every time i.e

当我将 的值递减a-1 时,console.log( a )每次都应该减少 1,即

100 99 98 ......

But console.log( a )is always giving 100

console.log( a )总是给予100

newbie to javascript here please be gentle. thanks.

javascript 新手请保持温和。谢谢。

回答by Adil

You should not pass ain parameter of timerfunction to access the global variable a. When ais passed to timer function the value of global variable is used but in timer the parameter variable is local to timer function and changing the value of it wont change the value of global variable. It means you have two variables in your code having name aone is global and other is local to timer function and you are changing value of local variable of timer.

你不应该传入函数的a参数timer来访问全局变量a。当a传递给定时器函数时,使用全局变量的值,但在定时器中,参数变量是定时器函数的局部变量,改变它的值不会改变全局变量的值。这意味着您的代码中有两个变量,a一个是全局变量,另一个是定时器函数的局部变量,并且您正在更改定时器局部变量的值。

a = 100;
var i = setInterval( timer, 1000 );

function timer() {
    console.log( a );
    if ( a < 1 ) {
        console.log( 'Reaching Stop' ); 
        clearInterval( i );
        return;         
    } 
    a -= 1;
}

回答by Jason P

When you pass the variable as a parameter to a function, you create a closure, which creates new scope for the variable.

当你将变量作为参数传递给函数时,你创建了一个闭包,它为变量创建了新的作用域。

Since the variable is global, you don't need to pass it in:

由于变量是全局变量,因此您无需传入:

http://jsfiddle.net/FBVTT/

http://jsfiddle.net/FBVTT/

var a = 100;
var i = setInterval(timer, 1000);

function timer() {
    console.log(a);
    if (a < 1) {
        console.log('Reaching Stop');
        clearInterval(i);
        return;
    }
    a -= 1;
}

Here's an MDN page on closures.

这是一个关于闭包MDN 页面