Hey Programmers, I hope everyone is doing well during the Pandemic.

I had no plans on how many parts Redux blogs will be, but the deeper I understand something I would share the challenge and how I managed to implement a good solution for it.

First, What is Intervals and why they are very important?

setInterval is a method that calls a function or runs some code after specific intervals of time, as specified through the second parameter.

At this part I wanted to make all functions I created in Action Creator to work, and as it’s a game, I created functions to check the state every few seconds to keep the game real.

For an example I have functions that:

  • increase Score and decreaseScore.
  • increaseHealth and decreaseHealth
  • increaseBodyTemp and decreaseBodyTemp
  • moreFire and fillWell

All those functions will run on conditions, increasing score and decreasing will depend on how the player is doing.

MoreFire function will run every few seconds to feed the fire and if fire goes below 10% a function will check that case and consume some firewood.

Body temperature and Health will depend on the temperature of the player if the weather gets too cold and the fire isn’t live.

And All this works great with SetIntervals:

increaseHealthInt = setInterval(() => {      if (this.props.fire > 0 && this.props.health <= 90) {            this.props.increaseHealth()         }}, 4000)

This interval runs every 4 seconds to check, if there is fire and the health needs improvement, if true, it calls the function I created in my Action Creator.

Second, ClearInterval:

A function or block of code that is bound to an interval executes until it is stopped. To stop an interval, you can use the clearInterval() method.

It’s very important to wrap the interval in a variable, in case you need to clear it.

clearInterval(this.increaseHealthInt)

You can also clear all your intervals in componentWillUnmount()

componentWillUnmount() {clearInterval(this.weatherInt, this.wellInt, this.fireInt, this.decreaseScoreInt, this.decreaseHealthInt, this.decreaseBodyTempInt, this.increaseHealthInt, this.increaseBodyTempBy10Int, this.gameInt);}

I hope this was helpful

Mokhtar

Web Developer | World Traveler | Positive Attitude

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store