undefinedfix
Sign in

JS declares the global variable in advance, then assigns a value in the local scope, and then gets the value in the global scope?

rauf101 edited in Mon, 19 Sep 2022

JS declares a variable outside the local scope in advance, then assigns a value inside the local scope, and then takes the assigned variable outside the global scope. But it can't be read. What's the reason?

            var new_time;
            setInterval(function(){
                if(code_time<=30&&code_time>0){
                    code_time--;
                    $("#send-code").text(code_time+"S");
                    new_time=code_time;
                    console.log(new_time) //输出正常值
                }
                // else{
                //     $("#send-code").removeAttr("disabled");
                //     $("#send-code").text("发送验证码");
                //     $("#send-code").css("background","#e32f1c");
                // }
            },1000);
            console.log(new_time) // 输出undefined

图片描述

I want to read the assigned variable new in the local outside the global_ But read the top unassigned variable and output undefined

7 Replies
iamdual
commented on Mon, 19 Sep 2022

Setinterval is executed asynchronously. That is to say, when printing, the function has not been executed, so it does not change, and returns undefined. You can do that :

       var new_time;
       async function fn(){
            if(code_time<=30&&code_time>0){
                code_time--;
                $("#send-code").text(code_time+"S");
                new_time=code_time;
                console.log(new_time) //输出正常值
            }
            // else{
            //     $("#send-code").removeAttr("disabled");
            //     $("#send-code").text("发送验证码");
            //     $("#send-code").css("background","#e32f1c");
            // }
        }
        let timer = setInterval(fn,1000);
        fn().then(() => {console.log(new_time)})
 
GeorgeP
commented on Mon, 19 Sep 2022

Your setinterval is asynchronous and the execution order is var new_ time; console.log (new_ Finally, execute settinterval

scgxu
commented on Tue, 20 Sep 2022

The setinterval function does not execute its callback function immediately, but asynchronously.

Execution to console.log The setinterval callback (that is to say, to new) is used_ Time assignment function) has not been executed, so it has not been given new_ Time assignment.

SpenserWilson1
commented on Tue, 20 Sep 2022

Understand asynchronous first

Jerry
commented on Tue, 20 Sep 2022
var new_time;
console.log(new_time);
setInterval(...)

This is the execution order of your screenshot code. You first define the variable new_ Time, 1 s after the assignment, printed on the outside of the timer.

hamid
commented on Tue, 20 Sep 2022

Generally speaking, timer is asynchronous. You can see the event loop. https :// segmentfault . com / a / eleven ...

Understand these, and then encounter similar problems OK

user67275
commented on Tue, 20 Sep 2022

Simplify the code, do an experiment can understand a 7788

function test() {
    var new_time;
    console.log("[1]", new_time);
    let counter = 0;
    const timer = setInterval(function() {
        new_time = new Date();
        console.log("[2]", new_time);
        if (++counter > 5) {
            clearInterval(timer);
        }
    }, 1000);
    console.log("[3]", new_time);
}

test()

Running results

[1] undefined
[3] undefined
[2] 2019-07-11T03:51:39.235Z
[2] 2019-07-11T03:51:40.236Z
[2] 2019-07-11T03:51:41.237Z
[2] 2019-07-11T03:51:42.237Z
[2] 2019-07-11T03:51:43.238Z
[2] 2019-07-11T03:51:44.238Z

Note that [1] is followed by [3], not [2]

As you can see, setinterval () The code in is executed after a certain time_ The initial value of time is more obvious. This is because of setinterval () Asynchronous code in is not on the same blocking line as the code in mainstream.

Next, we use async / await to wait for the asynchronous process to end

async function testAsync() {
    var new_time;
    console.log("[1]", new_time);
    let counter = 0;
    await new Promise(resovle => {
        const timer = setInterval(function() {
            new_time = new Date();
            console.log("[2]", new_time);
            if (++counter > 5) {
                clearInterval(timer);
                resovle();
            }
        }, 1000);
    });
    console.log("[3]", new_time);
}

testAsync()

output

[1] undefined
[2] 2019-07-11T03:54:52.675Z
[2] 2019-07-11T03:54:53.675Z
[2] 2019-07-11T03:54:54.675Z
[2] 2019-07-11T03:54:55.675Z
[2] 2019-07-11T03:54:56.675Z
[2] 2019-07-11T03:54:57.675Z
[3] 2019-07-11T03:54:57.675Z

You can see that [ three ] It is executed after the asynchronous end, because after the asynchronous process is encapsulated with promise, await is used to wait for it to end.

As for asynchronous process, I can't explain it clearly for a while

  • Asynchronous programming needs "consciousness"
  • Understanding async / await in JavaScript
  • From hell to heaven, node callback changes to async / await