I am practicing this simple countdown function in the console and the code works once I completed writing it and hit enter, but when I try to call it again (typed countDown();
), the console gives me this error message saying
"Uncaught TypeError: countDown is not a function".
I save the function in the variable countDown
and when I called the function, I simply typed countDown();
I checked there is no typing error. What did I do wrong, the code is as below...
var timeLeft = 10;
var countDown = setInterval(function(){
timeLeft--;
console.log(timeLeft);
if(timeLeft === 0){
clearInterval(countDown)
console.log("count down completed")
}
} ,1000);
I save the function in the variable countDown
No, you saved _the result of setInterval
in that variable.
setInterval
returns a timer ID, not a function.
If you want to save a function in a variable, you need to actually save the function in the variable.
I think you should declare the function outside setInterval, I've provided below example for your reference:
var timeLeft = 10;
var countDown = setInterval(timer, 1000 );
function timer() {
console.log(timeLeft);
if (timeLeft < 1) {
console.log('Count down completed');
clearInterval(countDown);
return;
}
timeLeft -= 1;
}
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.