Skip to content
Advertisement

Why every time that setInterval does a cycle, it throws the every data of all cycles?

I’m doing a Discord Bot and I have a infinite loop with setInterval each 10s but every loop that the setInterval does, it gives me every data of each loop, so I’d like to know how can I do to get only the last data of the last cycle, not every one.

JavaScript

This is how the messages are shown:

enter image description here

As you can see, now it’s giving each change not all the data of each cycle enter image description here

Advertisement

Answer

Every time your setInterval runs, it loads the page fresh, gathers information in ‘clock’, and sends it via discord. The problem is, it does not know what it has already sent you, so you’ll get some of the same data every time.

The solution to that is to save the data it finds, and then only create a discord message if the current batch of data is different from all of the previous data.

So you want some kind of data store:

JavaScript

And then once you’ve gotten the current clock back, you want to check if it is NOT in the data store.

JavaScript

If it isn’t, then you know that you have a new piece of data to send.

JavaScript

So all in all you have something like:

JavaScript

While we’re at it though, there’s no real reason to fire up a new browser window every 10 seconds, it will probably be easier on your computer to load the page once and then simply refresh every 10 seconds.

JavaScript

Now, to make sure that your page function (clock) finds a new data point each time, we need to pass our past data points in to it:

JavaScript

Now, inside of the page function you’ll have access to the old data points.

Instead of

JavaScript

Check if the data point exists in your clocks array, and only return it if it’s new.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement