0

var data = Math.random()

setInterval(function interval() {
  console.log(data)
}, 1500)

I want to get the updated value of var data from setinterval function, but I'm not able to get the updated value of var data, don't change this line

var data = Math.random()

This line is mandatory. I can't change this line somehow. How can I get the updated value?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Munny Reol
  • 41
  • 7

2 Answers2

0

You would need to convert it to a function, to be recalculated in each setInterval:

const data = () => Math.random();

setInterval(function interval() {
  console.log(data());
}, 1500);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
AdriSolid
  • 2,570
  • 1
  • 7
  • 17
  • I know this basic. but my main question is this https://stackoverflow.com/questions/66375798/how-to-get-updated-value-of-react-usestate-hook-from-setinterval-function-in-hig please solve this problem – Munny Reol Feb 26 '21 at 09:13
0
var data = Math.random()

setInterval(function interval(){
console.log(data)
},1500)

In this case data variable is not updated in each interval thats why this data is printing same value

Other way to do this :

setInterval(function interval(){
    var data = Math.random()
    console.log(data)
    },1500)

Or you can define a function for random number in top and you can call in inside of interval

SHUBHAM SINGH
  • 371
  • 3
  • 11
  • that's not possible to define the data variable inside setInterval. because in my code, i fetch some data from api & use the data outside of setinterval. & now i have to get the same api data inside the setInterval.. how its possible – Munny Reol Feb 26 '21 at 09:10
  • I know this basic. but my main question is this https://stackoverflow.com/questions/66375798/how-to-get-updated-value-of-react-usestate-hook-from-setinterval-function-in-hig please solve this problem – Munny Reol Feb 26 '21 at 09:14