简体   繁体   中英

undefined variable within a setInterval callback

I am implementing a simple countDown function that, given a num in seconds, counts down num, num-1, ..., 0 and console.log s "Ring Ring Ring!!!" .

When num is 0 using JavaScript built in setInterval method. The problem with my implementation is that the variable num is printing as an undefined variable.

I've looked at this for an hour now and can't sort it out. Can someone help out? Thanks!

function countDown(num) {
    var timer = num * 1000;
    var intervalId = setInterval(function(num) {
        if (timer !== 0) {
            console.log("Timer: ", num);
            num--;
            timer -= 1000;
        } else if (timer == 0) {
            console.log("Ring Ring Ring!!!");
            clearInterval(intervalId);
        }
    }, 1000);
}

You've num in setInterval function just remove that

 function countDown(num) { var timer = num*1000; var intervalId = setInterval(function(){ if(timer !== 0){ console.log("Timer: ", num); num--; timer -= 1000; } else if(timer == 0){ console.log("Ring Ring Ring!!!"); clearInterval(intervalId); } }, 1000); } countDown(20);

Remove the param num from here:

setInterval(function(num));
                     ^

That param is hiding the outer param from function countDown(num) {...}

 function countDown(num) { var timer = num * 1000; var intervalId = setInterval(function() { if (timer !== 0) { console.log("Timer: ", num); num--; timer -= 1000; } else if (timer == 0) { console.log("Ring Ring Ring!!!"); clearInterval(intervalId); } }, 1000); } countDown(1);

There is no need for you to pass num as an argument to the anonymous function

So the below code should work : -

function countDown(num) {
    var timer = num*1000;
    var intervalId = setInterval(function(){  //removed num argument
        if(timer !== 0){
            console.log("Timer: ", num);
            num--;
            timer -= 1000;
        } else if(timer == 0){
            console.log("Ring Ring Ring!!!");
            clearInterval(intervalId);
        }
    }, 1000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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