Ad

Build A Nested Interval Loop

- 1 answer

I want to build an interval loop which triggers every day. Inside this loop should be again a interval loop, which triggers every 20 minutes. So now, I am curious, if I could just build it like this:

updatePeriodically() {
    window.setInterval(() => {
        console.log('Fetch daily sensor update!')
        getInitData()
            .then((results) => {
                this.setState({ dataSensor: results })      
            })
            window.setInterval(() => {
                console.log('Fetch 20 minute sensor update')
                getData()
                    .then((results) => {
                        this.setState({ dataSensor: results })
                })
            }, UPDATE_INTERVAL)

    }, DAILY_INTERVAL)
} 

I just want to know, if this triggers a new 20 min-interval loop every day and does not stops the old one, so in the end after some days, I have like four 20-update loops? Or maybe someone knows, how to do this a better way?

Ad

Answer

I am guessing you could refine your interval timer by either checking if the interval has already started before (your internal interval), or by using only one interval and repeat getInitdata only once every so many times, as such:

updatePeriodically() {
    var remaining = 0;
    window.setInterval(() => {
        if (remaining <= 0) {
            console.log('Fetch daily sensor update!');
            getInitData().then((results) => {
                this.setState({ dataSensor: results });
            });
            remaining = DAILY_INTERVAL;
        } else {
            remaining -= UPDATE_INTERVAL;
            console.log('Fetch 20 minute sensor update');
            getData().then((results) => {
                this.setState({ dataSensor: results });
            });
        }
    }, UPDATE_INTERVAL);
} 

this has the advantage that it would only use 1 loop to do the periodic updating, and no extra intervals will be started.

I would however recommend not creating this update loop inside a component. I am assuming the data you want to display is managed by a store, and you should rather have a central place that runs this "polling" update, so that all components get the new data at once, instead of each component implementing such a polling function. A bonus would be that all components that are dependent from this data get their new state data at the same time.

Ad
source: stackoverflow.com
Ad