I'm making a simple game, and it's just taking the position of the user's touch and knowing if he has touched the object or not, but it turns out that if I repeatedly tap on the screen the object starts pausing very quickly, it's as if the interval that makes the object move will pause right when I touch the screen, but it's a very short pause as I said before:
//En este evento recojo la posición del toque
document.body.addEventListener('touchstart', function(event){
var yFinger = event.touches[0].clientY; localStorage.yFinger = yFinger;
var xFinger = event.touches[0].clientX; localStorage.xFinger = xFinger;
}, false);
Well, it seems that when this event is executed, it pauses for a few thousandths of a second the interval that I have in another function that is in charge of moving the object, here I leave the interval that I move the object (obviously simplified and reduced):
//Un sencillo ejemplo de un intervalo moviendo el objeto del top (está en una función diferente)
var yPos = 0;
setInterval(function() {
yPos = yPos + 10;
document.getElementsByClassName("object")[0].style.top = yPos;
}, 25);
Thanks for any help, I think the problem is in the event where I collect the position of the touch, but I don't know how I could correct it.
Note: in <head>
the page I have entered the following to eliminate the 300ms delay in the mobile browser: (I know that it is not eliminated in all browsers just with that, but for now it works for me if it works in Chrome)
<meta name="viewport" content="user-scalable=no">
The strange thing about it is that this problem in Safari does not happen to me.
setInterval
, likesetTimeout
, does not guarantee that it will be executed at the indicated interval, but that it will be executed when possible after at least the indicated time has elapsed. It can be 25ms, 50 or 200. It is possible then that processing the event is delaying the execution of the rest of the script.I could suggest a few things:
Use CSS animations (
transform
), this activates hardware acceleration, if available.If you're just moving an object, use an id and
getElementById
, instead ofgetElementsByClassName
.Use another event. If what you want is to know if it touched the object, why not listen to the
click
ortouchstart
of the object?Using the function
window.requestAnimationFrame
solves everything, this way the number of images per second is not forced, and the browser can optimize it so that the animations will be much smoother.Guide to know its uses: CSS Tricks