Touch “Hold” Function: Button Held Down In NativeScript

Tonight I needed to run a function constantly while a button is being held down in my app. I found the gestures functionality and it had what I needed but I had to do some work to get it to perform what I was after.

My task was this, when someone puts their finger down on a ‘Record’ button I need to store what the sound level was every 10/1000 of a second. So here’s what I did.

Using Gestures Touch to Define “Hold”

When the page is loaded I assign the button element to a variable then I add the on touch function. It’s important to declare that button’s variable at the beginning of your JS so it’s available in all functions. Also important to require your view module and gesture. Here’s a snippet that covers all of that:

Now that I’m calling a function, let’s tell that function what to do. We have our “soundlevel” view which is just a button with id=”soundlevel” and we’ve assigned an action of “on” for it when gesture touch occurs. The gesture touch passes args that include “action” as a property. That property can be “down”, “up” amongst other things, but these are what we need. So now let’s build a function to handle the hold.

Note: barWidth is an integer I end up assigning as a percentage of the screen width. This way I can give a visualization of sound level.

Here we check wether the action is up or down and do our desired functionality based on that. If it’s “up” that means the finger has been lifted from the screen so we stop everything.

If the action is “down” that means the user has just pressed the button. So we user the timer library and set an interval. Basically every 10/1000 of a second we perform a calculation of the sound level and push that to our array of sound levels. Now we can analyze that and do what we want to do!