+ 2
How to access a variable inside setInterval function in global
Trying to access the number variable outside the function and i get error,help me fix want to console.log those random numbers as they change code: setInterval(function(){ number = Math.floor((Math.random()*10)); }, 1000); console.log(number); https://code.sololearn.com/WyD6tnhAKXjX/?ref=app
21 ответ
+ 4
You cannot access local variable globally.
Why you need to access outside the function?
+ 1
J4D3N
setInterval(function(){
window.number = Math.floor((Math.random()*10));
}, 1000);
+ 1
But it's bad practice. There absolutely no reason to do that. And I've never met a single case when I needed to do that.
+ 1
J4D3N Not in console. You can define 'window.number' variable inside your function and it's the same if you define 'number' variable in your main code flow aka global. Then you can access that variable. But if it is a local variable inside a function you can not access it from outer scope. And the only way (I know) to do that is as I did in the code above.
+ 1
But remember that such properties are not variables! So function.number = 0 //property
let number = 0//variable
These too things are completely different.
+ 1
I rewrote your code a bit. Just to give some food for thought. Notice how I declared only 1 global scope variable "start", and everything else is processed by functions. You may ask: "Why it is important?". Well, It is important because you don't pollute the global scope, and doing so you will avoid many mistakes in future. I used some advanced stuff here tho, such as ES6 destructuring, closure. But the code is really simple and hopefully, you'll get the idea.
https://code.sololearn.com/Wg6pwOgt3kJk/?ref=app
+ 1
السلام عليكم ورحمة الله
+ 1
عباس زكريا اسحق وعليكم السلام ورحمة الله وبركاته
0
Just define that variable in global scope. Or you could define it internally as 'window.number = ...'
0
But if you really want to access a variable that is local to function then you need to add property to that function