javascript setInterval()和变量范围 [英] javascript setInterval() and Variable Scope

查看:492
本文介绍了javascript setInterval()和变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经在这里阅读了几个相同题目的问题,但仍然找不到解决我的问题的方法。我正在研究一个基本的JavaScript倒数计时器,我坚持更新 a 变量的值。

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

函数计时器(a){
console.log(a);
if(a <1){
console.log('Reaching Stop');
clearInterval(i);
return;
}
a - = 1;
}

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

  100 99 98 ...... 

code> console.log(a)总是给出 100



新手到javascript这里请温柔。
thanks。

解决方案

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

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

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


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 a variable.

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 a by -1, console.log( a ) should be 1 less every time i.e

100 99 98 ......

But console.log( a ) is always giving 100

newbie to javascript here please be gentle. thanks.

解决方案

You should not pass a in parameter of timer function to access the global variable a. When a is 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 a one is global and other is local to timer function and you are changing value of local variable of timer.

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

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

这篇关于javascript setInterval()和变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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