How to call a function repeatedly?

I want to call an event repeatedly, as long as a button is pressed. i know the touch event has ‘began’ and ‘ended’ phases. Is there something like a ‘pressed’ phase that will allow me to call a function/event for as long as the button is pressed?

Set a variable at the top of the lua file called holding, which is turned to true in the begin phase and false in the ended phase. Then test this variable in an enterFrame listener to decide whether to run the code.

One thing to be careful of is if the user slides their finger off the button, I don’t believe you get an ended phase. So you might need to set up a touch listener on the whole screen so you can check when a touch event happens outside of the button and reset holding to false.

The problem with that solution is that enterFrame is called 30 time/sec or 60 times/sec, depending upon config.lua settings.

What if someone wants to call the function less frequently? say, after every 0.1 seconds

You could call a function using timer.performWithDelay that repeats every x milliseconds, and check the holding variable before running the required code within that.

Generally though I prefer to simulate my own repeating timer within enterFrame as it gives me more control. Say I have an event that happens every 4 seconds at the start of a level, but I want to get increasingly more frequent. I can then just adjust the number that I test the timer against on the fly, and don’t have to stop the old timer and start a new one.

Set a variable at the top of the lua file called holding, which is turned to true in the begin phase and false in the ended phase. Then test this variable in an enterFrame listener to decide whether to run the code.

One thing to be careful of is if the user slides their finger off the button, I don’t believe you get an ended phase. So you might need to set up a touch listener on the whole screen so you can check when a touch event happens outside of the button and reset holding to false.

The problem with that solution is that enterFrame is called 30 time/sec or 60 times/sec, depending upon config.lua settings.

What if someone wants to call the function less frequently? say, after every 0.1 seconds

You could call a function using timer.performWithDelay that repeats every x milliseconds, and check the holding variable before running the required code within that.

Generally though I prefer to simulate my own repeating timer within enterFrame as it gives me more control. Say I have an event that happens every 4 seconds at the start of a level, but I want to get increasingly more frequent. I can then just adjust the number that I test the timer against on the fly, and don’t have to stop the old timer and start a new one.