Why is setTimeout game loop experiencing lag when touchstart event fires? - javascript

This is a rather specific problem I'm having. The glitch only seems to appear in the latest update of Chrome for Android, so here are the specs:
Application Version:
Chrome 45.0.2454.84
Operating System:
Android 4.4.4; XT1031 Build/KXB21.14-L2.4
I'm using a Moto G, but the glitch also occurred on a Samsung running the same version of Chrome. Anyway, the problem is clearly that touchstart events interrupt my window.setTimeout game loop. Here's the code:
(
function rafTouchGlitch() {
/////////////////
/* FUNCTIONS. */
///////////////
function touchStartWindow(event_) {
event_.preventDefault();
}
///////////////////////
/* OBJECT LITERALS. */
/////////////////////
var engine = {
/* FUNCTIONS. */
start : function(interval_) {
var handle = this;
(function update() {
handle.timeout = window.setTimeout(update, interval_);
/* Draw the background and the red square. */
display.fillStyle = "#303030";
display.fillRect(0, 0, display.canvas.width, display.canvas.height);
display.fillStyle = "#f00000";
display.fillRect(red_square.x, red_square.y, 20, 20);
/* Update the square's position. */
red_square.x++;
if (red_square.x > display.canvas.width) {
red_square.x = -20;
}
})();
},
/* VARIABLES. */
timeout : undefined
};
red_square = {
/* VARIABLES. */
x : 0,
y : 0
};
/////////////////
/* VARIABLES. */
///////////////
var display = document.getElementById("canvas").getContext("2d");
//////////////////
/* INITIALIZE. */
////////////////
window.addEventListener("touchstart", touchStartWindow);
engine.start(1000 / 60);
})();
This code works fine in any other browser and even in previous versions of Chrome. It worked fine in the last release, but for some reason now there's a problem. I'm not sure if this is a bug on Chrome's end or if they're doing something new and I'm the one not covering my bases, but the fact remains that there's a glaring lag in my game loop when touchstart events fire.
Here's a fiddle: https://jsfiddle.net/dhjsqqxn/
Tap the screen and see how the red square lags! It's ridiculous. You can basically freeze the Timeout object by tapping the screen fast enough.
If you have an Android phone, I urge you to update Chrome and visit the link to see what I mean. If this is a bug it's a huge one, considering how valuable setTimeout is and how vital touchstart is on mobile. If it's not a bug, I'd really like to know what I'm doing wrong.
Thanks for your time!

See https://bugs.chromium.org/p/chromium/issues/detail?id=567800
Android Chrome does not run scheduled(setTimeout/setInterval) callbacks during touchmove.
As a workaround you can try window.requestAnimationFrame() or run the callback manually in touchmove event which would require to keep/check a last-run time.

Do "return false;" at the end of the touchstart func.
for a swipe the following jquery without jquerymobile..
$("#id").on({'touchstart' : functionforstart, 'touchmove' :onmove, 'touchend' : functionforend});
functionforstart(e){ e.originalEvent.touches[0].pageX usw.. return false;}
function onmove(e){lastMove=e}
function functionforend(){lastMove.originalEvent.touches[0].pageX} usw.. e.prefentDefault(); }
That works for me.. var lastMove have to be global and you need a touchmove step to get the position in touchend.. hope this is also what you needed..

Related

Force update of ScaleLine Control in openlayers 2

I'm using Openlayers 2 and I'm creating a map app. I'm using apache cordova so it's just javascript/html/css.
It works fine for most cases but when I zoom in and out a bunch of times (with my fingers on a touchscreen) sometimes the scaleline stops updating. Moving the map around and zooming in/out some more usually get's it starting again.
My question is: Is there a way to force the ScaleLine control to redraw (other than moving around the screen and zoom in/out randomly). Like, is there a function I can run on, say, the click of a button to force redrawing?
I've tried
map.Control.Scaleline.update();
map.Control.Scaleline.draw();
But it doesn't work
Thanks!
PS:
I've tried opening the app from chrome on a desktop and since I don't have the touch screen capability there I can't reproduce the error
By looking at OpenLayers.debug.js I could see that scaleline is updated at "moveend" event which is only triggered when touch is completed (which it isn't if the user doesn't let the touch drag finish for example by zooming)
"move" always triggers, so I solved it by triggering "moveend" on "move" event.
map.events.on ({
"move": function () {
map.events.triggerEvent("moveend");
}
}
});
It removes the detail of adding certain events only on "moveend" but it solves the problem. Please comment if you have a better solution!
#atwinther was almost right. The solution is to watch for "touchend" and then send a moveend event. Only the latest browsers support this, however, so it might still be buggy for some people. At the least, according to Mozilla, this should work for the latest Firefox and Chrome: https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent
This is what I did that worked, with non-essential code ellided:
var SYP = {
init: function() {
this.map = new OpenLayers.Map("map");
// workaround for ol2 bug where touch events do not redraw the
// graticule or scaleline
this.map.events.on ({
"touchend": function () {
SYP.map.events.triggerEvent("moveend");
}
});
},

Android 4 Chrome hit testing issue on touch events after CSS transform

I'm having issues with the combination of CSS transforms and touch event hit testing. This only reproduces for me in Chrome on Android 4 (stable and beta). iOS Safari, as well as Chrome desktop with touch emulation both appear to be working fine.
I'm almost positive this has to be a bug, so I think I'm mostly looking for workarounds here.
The issue is that hit testing for touch only seems to work for where the element was before the transform, not the final position. You can see an example on my jsfiddle (only on Android 4 Chrome):
jsfiddle: http://jsfiddle.net/LfaQq/
full screen: http://jsfiddle.net/LfaQq/embedded/result/
If you drag the blue box half way down the screen and release it will snap back to the top. Now, if you try dragging from the top half of the page again, no touch will register. The touch events aren't even fired on the element. However, if you attempt to touch the bottom of the element, it works fine. You can then try moving it up from the bottom, and observing that hit testing no longer works on the bottom, but works on the top.
This is how I'm handling the events:
function handleTouch(e) {
console.log("handle touch")
e.preventDefault();
switch(e.type){
case 'touchstart':
console.log("touchstart");
touchOriginY = e.targetTouches[0].screenY;
break;
case 'touchmove':
console.log("touchmove");
el.innerHTML = e.targetTouches[0].screenY;
var p = e.targetTouches[0].screenY - touchOriginY;
el.style[TRANSFORM] = 'translate3d(0,' + p + 'px' + ',0)';
break;
case 'touchcancel':
console.log("touchcancel");
// Fall through to touchend
case 'touchend':
//console.log("touchend");
//el.style[TRANSITION] = '.4s ease-out';
el.style[TRANSFORM] = 'translate3d(0,0,0)';
break;
}
}
el.addEventListener('touchstart', handleTouch);
el.addEventListener('touchend', handleTouch);
el.addEventListener('touchmove', handleTouch);
el.addEventListener(TRANSITION_END, function(e) {
console.log("transition end")
el.style[TRANSITION] = '';
});
I don't have any problems with the transforms in touchmove, as those aren't new touches to be detected anyways.
Any suggestions?
This is an unusual bug in Chrome.
Essentially the hit targets for an element is recorded during a layout pass by the browser. Each time you set innerHTML, the browser will relayout and the last time this is done, is before the touchend event is fired. There are a couple of ways around it:
OPTION 1: You can set a touch handler on the body element and check the target of touch event to see if it is touching the red block. Tip of the cap to Paul Lewis for this approach.
http://jsfiddle.net/FtfR8/5/
var el = document.body;
var redblock = $('.splash-section');
function handleTouch(e) {
console.log("handle touch")
if(e.target != redblock) {
return;
}
....
OPTION 2: Set an empty touch callback on the document seems to fix the problem as well - according to some of the linked bug reports, this causes the hit testing to be done on the main thread which is a hit on performance but it properly calculates the hit targets.
http://jsfiddle.net/LfaQq/2/
document.body.addEventListener('touchstart', function(){});
OPTION 3: Set innerHTML after the transition has ended to force a relayout:
el.addEventListener(TRANSITION_END, function(e) {
console.log("trans end - offsettop:" + el.offsetTop);
el.style[TRANSITION] = '';
el.innerHTML = 'Relayout like a boss!';
});
I've created a bug report here and Rick Byers has linked to a related bug with additional info: https://code.google.com/p/chromium/issues/detail?id=253456&thanks=253456&ts=1372075599

touchmove/MSPointerMove event not firing in Windows 8

I'm just a lowly uC programmer who's trying to put together a little web interface for his boss. I've got everything working so far except being able to select a square on a canvas using touch input.
This is on a Samsung Slate 7 tablet running Windows 8 and IE10
I've distilled the code down to pretty much the bare essentials here:
var cxt;
var c;
window.onload = function () {
c = document.getElementById('displayCanvas');
cxt = c.getContext('2d');
/*
c.addEventListener("MSPointerUp", mouseUp, false);
c.addEventListener("MSPointerMove", mouseMove, false);
c.addEventListener("MSPointerDown", mouseDown, false);
*/
c.addEventListener("touchend", mouseUp, false)
c.addEventListener("touchmove", mouseMove, false);
c.addEventListener("touchstart", mouseDown, false);
}
function mouseDown(downE) {
window.console && console.log("down");
};
function mouseMove(moveE){
window.console && console.log("move");
}
function mouseUp() {
window.console && console.log("end");
}
I get both the start and end events, using both the MSPointer and the "normal" javascript touch events, however the "move" event doesn't register.
I'm sure it's something really simple I'm missing here, thanks for helping me out!
I'm assuming you are interacting with the HTML page in desktop IE on Windows 8. In desktop IE, the MSPointerMove is not firing on that canvas because the default behavior when the user moves their finger around on the screen is to pan the content. If you style the canvas with the following snippet your MSPointerMove event should be detected.
style="-ms-touch-action: none"
Here's a great article on how to get touch working on many browsers. http://blogs.msdn.com/b/ie/archive/2011/10/19/handling-multi-touch-and-mouse-input-in-all-browsers.aspx
The Samsung Slate 7 tablets have a bug in older versions of the drivers that might be relevant. I saw another answer tagged [internet-explorer-10] that had the details. Have you updated your driver?

Controlling events on Apple Ipad's Safari

Well, this will be a tough one. I think i have exhausted all my options, let's see if you can come up with something better.
I have a horizontal carousel and am using touchstart, touchmove, touchend to control it. For the sake of this example, the html structure is something like:
<div>
<ul id="strip">
<li><a>...</a></li>
<li><a>...</a></li>
...................
</ul>
</div>
I have separated my eventhandlers to behave a bit differently from mouse to touch events, so, thinking only of touch, I have:
var strip = document.getElementById('strip');
strip.addEventListener('touchstart', touchStartHandler);
document.addEventListener('touchmove', touchMoveHandler);
document.addEventListener('touchend', touchEndHandler);
I want the horizontal scrolling to work even if the user has his finger outside my strip, so I attached the touchmove and touchend event to the document.
At first, I thought it would be natural to, while the user was scrolling my carousel, for the browser to stay put, so my touchMoveHandler looked something like:
function touchMoveHandler(evt){
evt.preventDefault();
...................
}
... this way, the browser wouldn't pan vertically when the user's finger positioned varied in the Y axis. Our usability guy, thinks otherwise, and I actually agree with him now. He wants the browser to respond normally, unless the movement of the finger is totally or near perfectly horizontal.
Anyway, this is probably too much information, so I am going to detail my actual problem now. This is a snippet of the prototype I'm working on as a proof of concept:
var stopY, lastTime, newTime;
var touchStartHandler(evt){
...
stopY = true;
lastTime = new Date();
...
};
var touchMoveHandler(evt){
...
//this following code works like a setInterval, it turns stopY on and off every 1/2 sec
//for some reason, setInterval doesn't play well inside a touchmove event
newTime = new Date();
if(newTime - lastTime >= 500){
stopY = !stopY;
lastTime = newTime;
}
...
if(stopY){
evt.preventDefault();
}
...
}
I am absolutely sure this code is pristine, I debugged it with console logs and everything is doing what it's supposed to do except for the computing of the browser panning through the stopY variable.
If I run the code starting with stopY = true, there is no browser panning, if I start with stopY = false, the browser pans as expected. The problem is that I would expect this behaviour to change every half a second and it doesn't.
I hope I didn't complicate this too much for you, but this is really specific.
Update:
You can try the following links (on an Ipad, or Iphone):
http://andrepadez.com/ipadtouch
http://andrepadez.com/ipadtouch?stopy=false
use view source, to see the whole code
Can you try stopY = !stopY;?
UPDATE
Once you execute preventDefault(), scrolling will can not return until touchend fires or you enable it. The following may give you the behavior you are looking for:
if(stopY){ return false; }
else { return true; }
or for simplicity just return !stopY;...

Android browser garbles events for two taps in quick succession

I'm trying to use JavaScript and jQuery to capture touch events. But I'm seeing some very odd behavior in the Web browser on Android 2.3.2: whenever I tap the screen, and then quickly tap somewhere else on the screen, the browser:
momentarily shows an orange border and highlight over the entire screen, and
sends me the wrong events.
The orange border seems to be just a related symptom of the same underlying problem, so I'm not too worried about it -- it's actually convenient for being able to tell when the browser is screwing things up. What I really want to know is, how can I consistently get the right touch events for two quick taps? I believe that when that problem is solved, the orange border will go away as well.
What follows are all the painful details I've worked out so far.
Here's a page that shows the problem and displays lots of diagnostic information about the details and timing of each event that's received. You're sure to get the orange flash / bad events if you tap inside the blue rectangle, then quickly tap inside the black rectangle.
My jQuery code is pretty standard. The log function's implementation isn't important; the problem is that the browser doesn't call it when it should.
el = $('#battle');
el.on('touchstart', function(event) {
log(event);
return event.preventDefault();
});
el.on('touchend', function(event) {
return log(event);
});
el.on('touchcancel', function(event) {
return log(event);
});
el.mousedown(function(event) {
log(event);
return event.preventDefault();
});
return el.mouseup(function(event) {
return log(event);
});
More details on the phenomena I described initially:
Orange border and highlight: This is the same orange border and highlight that the browser draws around a hyperlink when you click it. But there are no hyperlinks on the page, and the browser draws this orange border around the whole screen -- or more specifically, around the outer <div id="battle"> that I'm hooking events on via jQuery.
Wrong events: In my touchstart event handler, I'm calling event.preventDefault(), to tell the browser not to scroll, not to synthesize mouse events, etc. Therefore, I expect to get only touchstart and touchend events. And I do, for the first tap. But instead of touchstart/touchend for the second tap, I get all number of combinations of touch events, synthesized mouse events, and the occasional touchcancel for the second tap, or even repeated events for the first tap. Details below.
This behavior also only occurs in very particular circumstances:
The first tap must be short (less than ~200ms).
The second tap must come quickly thereafter (less than ~450ms after the first tap's touchstart).
The second tap must be at least 150 pixels away from the first tap (measured along the diagonal from the coordinates of the first tap's touchstart).
If I remove my code that hooks mousedown and mouseup, the orange rectangles no longer appear. However, the touch events are sometimes still garbled.
As far as what I mean by the events being garbled, here's what I see. When I write "1:", that means the events are for the first tap's coordinates; "2:" means the second tap's coordinates. I saw the following patterns of events (percentages indicate how many times each one came up after 100 trials):
(50%) 1:touchstart 1:touchend 1:mousedown 1:mouseup (short delay) 2:mousedown 2:mouseup
(35%) 1:touchstart 1:touchend 2:touchstart 1:mousedown 1:mouseup 2:touchend
(10%) 1:touchstart 1:touchend 2:touchstart 1:mousedown 1:mouseup 2:touchcancel (short delay) 2:mousedown 2:mouseup
(3%) 1:touchstart 1:touchend 2:touchstart 2:touchend (short delay) 1:mousedown 1:mouseup
(2%) 1:touchstart 1:touchend 1:mousedown 1:mouseup (and nothing at all for the second tap)
Some combinations of events seem to come up more often depending on how quickly I tap, but I haven't quite nailed down the pattern. (Two quick, crisp taps seem more likely to come in under the second item above, whereas a more rapid-fire approach with less emphasis on crispness seems more likely to be the first item. But I haven't identified specific timing numbers that lead to each.) Similarly, the "short delays" indicated above can be anywhere from ~150ms to ~400ms; I haven't reverse-engineered the whole pattern there either.
If I don't hook mousedown and mouseup, the distribution is roughly this:
(40%) 1:touchstart 1:touchend 2:touchstart 2:touchcancel
(35%) 1:touchstart 1:touchend 2:touchstart 2:touchend (the actual desired behavior)
(25%) 1:touchstart 1:touchend (and nothing at all for the second tap)
So if I don't hook the mouse events, it works a third of the time; and if I was willing to pretend that touchcancel meant the same thing as touchend, I could get that up to 75% of the time. But that's still pretty sucky.
Alternatives I've already tried:
I've tried using jQuery Mobile's vmousedown and vmouseup events, but they aren't always triggered for the second tap, I suspect because of this same underlying event weirdness.
I could just forget about touch events entirely and only use the synthesized mouse events, but there's usually about a half-second delay between the physical tap and the delivery of the synthesized mouse event, whereas the touch events are immediate so I can be more responsive. I also want to prevent scrolling -- this is for a fullscreen game, and I'd rather not have the user accidentally scrolling the address bar back into view and blocking part of the game -- and doing preventDefault on the touchstart usually achieves that (though occasionally the second tap is actually able to scroll the screen despite my preventDefault... another reason I want to solve this whole event mess).
I've tried a third-party Web browser (Dolphin), but it has the same problems with events. So I'm guessing it's probably a problem with the way the underlying WebView delivers events to scripts.
Can anyone suggest a way to change my HTML, my event handlers, or anything else in order to reliably get touch events for two quick taps in succession?
Having tried to develop multi-touch HTML5 games in the Android browser (and trying them in other Android compatible browsers too), I think Android 2.x's browser simply does not properly support touch input. For starters, it doesn't support multi-touch which makes some kinds of game unplayable. (Obviously the phone supports multi-touch because you can pinch zoom etc., but the browser doesn't.) Then there are lots of problems with latency, touches 'sticking' and so on. I vaguely remember reading something about the phone's drivers for touch inputs not really working with true multitouch (i.e. it can detect either single touch or pinch zooms and that's it), but I don't have any references to back that up...
Apparently Android 4 (Ice Cream Sandwich) fixes it. So you might just have to wait for Android 4, which should be out soon anyway, and try again. Beyond that, Google have announced they're planning to replace the Android Browser with a mobile version of Chrome in future, so hopefully at least by then our browser touch-input woes will be over.
This is a theory: Wasn't able to test extensively
According to the init function in the soruce code of a webview, the statement setFocusable(true) is always called on a webview during its initialisation.
When I tried to make the view not focusable anymore using setFocusable(false) the error did not happen again. It seems the orange box does not appear. I was testing this on a small samsung phone running os 2.3.4. What I am sure of is that this orange box did not re appear.
In case this turns out to be true, it is highly likely that we can solve this without our own webview. What makes things more complicated is if setting the focusable property to false triggers other problems.
Finally, I do not think we can control this property from javascript (or can we?). Maybe You can declare that a specific control or the whole document is not an input or something like that? I am only extrapolating so bare that this may be false.
Edit: Regarding your comment on your question
I just created a blank application with only a Webview that loads your url after setting its focusable property to false. Please, if you have more resources to test it, I will upload it for you to try it. Here is the application
Have you tried using the jQuery Mobile events? You can find the decoupled widgets/plugins here:
https://github.com/jquery/jquery-mobile/tree/master/js
You'll probably need jquery.mobile.event.js and jquery.mobile.vmouse.js
Now you can simply bind to the tap, swipe etc. events within jQuery. Or is it necessary to differentiate between the start and end of a tap?
instead of attach all event using on you try this may be it works for you
$("...").bind("mousedown touchstart MozTouchDown", function(e) {
if(e.originalEvent.touches && e.originalEvent.touches.length) {
e = e.originalEvent.touches[0];
} else if(e.originalEvent.changedTouches && e.originalEvent.changedTouches.length) {
e = e.originalEvent.changedTouches[0];
}
// Handle mouse down
});
Have you tried attaching the event directly?
$(document).ready(function(){
var el, hypot, log, prev, resetTimeout, start, prevTouchX, prevTouchY;
var resetTimeout = null;
var start = null;
var prev = null;
var resetTimeout;
var hypot = function(x1, y1, x2, y2) {
var dx, dy, h;
dx = x2 - x1;
dy = y2 - y1;
h = Math.sqrt(dx * dx + dy * dy);
return Math.round(h * 10) / 10;
};
var logf = function(event) {
var div, table, values, x, y, _ref, _ref2, _ref3, _ref4, _ref5, _ref6;
if (event.type === "touchend"){
x = prevTouchX;
y = prevTouchY;
} else {
x = event.touches[0].pageX;
y = event.touches[0].pageY;
prevTouchX = x;
prevTouchY = y;
}
div = $('.log :first');
table = div.find('table');
if (table.length === 0) {
$('.log div:gt(1), .log hr:gt(0)').remove();
table = $('<table border style="border-collapse: collapse;"><tr>\n<th rowspan="2">Event</th>\n<th rowspan="2">X</th>\n<th rowspan="2">Y</th>\n<th colspan="4">From start</th>\n<th colspan="4">From prev</th>\n</tr><tr>\n<th>ΔT (ms)</th>\n<th>ΔX</th>\n<th>ΔY</th>\n<th>Distance</th>\n<th>ΔT (ms)</th>\n<th>ΔX</th>\n<th>ΔY</th>\n<th>Distance</th>\n</tr></table>');
div.append(table);
}
values = {
time: event.timeStamp,
x: x,
y: y
};
if (start == null) {
start = values;
}
if (prev == null) {
prev = values;
}
table.append("<tr>\n<td>" + event.type + "</td>\n<td>" + x + "</td>\n<td>" + y + "</td>\n<td>" + (event.timeStamp - start.time) + "</td>\n<td>" + (x - start.x) + "</td>\n<td>" + (y - start.y) + "</td>\n<td>" + (hypot(x, y, start.x, start.y)) + "</td>\n<td>" + (event.timeStamp - prev.time) + "</td>\n<td>" + (x - prev.x) + "</td>\n<td>" + (y - prev.y) + "</td>\n<td>" + (hypot(x, y, prev.x, prev.y)) + "</td>\n</tr>");
prev = values;
if(resetTimeout !== null){
window.clearTimeout(resetTimeout)
}
resetTimeout = window.setTimeout(function(){
start = null;
prev = null;
$('.log').prepend('<hr/>');
}, 1000);
};
var battle = document.getElementById("battle");
battle.addEventListener("touchstart",logf, false);
battle.addEventListener("touchmove",function(e){logf(e);e.preventDefault();}, false);
battle.addEventListener("touchend",logf, false);
battle.addEventListener("touchcancel",logf, false);
});
(Sorry if the code is really sloppy, I wasn't really paying much attention to the log function, but I made to make some minor changes as it wasn't firing correctly at my touchend event as event.touches[0].pageX is undefined at that point. Also, I wrapped it in a ready function, because I was just being lazy :-P)
Since this is only tracking the first touch (event.touches[0]), you can probably make some adjustments to test multi-touch by going down the touches array. What I've discovered on my android device (gingerbread) was that if you have two fingers down on the screen simultaneously, the touchend event will only fire when the last touch is let go; i.e. the second finger release.
Also, when I attached the mousedown/mouseup event listeners, then I got the same exact thing you did with the whole orange highlight thingy.
The device I tested on was a Samsung Droid Charge with OTA Gingerbread update.

Categories

Resources