Search code examples
javascriptsettimeouthammer.jsmobile-devicescleartimeout

clearTimeout/setTimeout on mobile devices


I have to make a button that has the following functions:

If you click on it, it should show some lines and hide them after 3 seconds, but if you click on the button before the 3 seconds are over the lines should hide as well.

I have written some code that is working perfectly on desktop browsers, but on mobile browsers it is not. Android devices seem to ignore my clearTimeout and on iphones it seems more like a "buttonPressed" event.

I have created a jsfiddle so that you can see what i have written.

var timeout = null;
var buttonCallback = function() {
    if( timeout === null ) {
        log('show lines');
        timeout = setTimeout(buttonCallback, 3000);
    }
    else {
        clearTimeout(timeout);
        timeout = null;
        log('hide lines');
    }
}


var hammerElement = Hammer(document.getElementById('showLines'));

hammerElement.on("touch", function(e) {
    e.preventDefault()
    buttonCallback();
});

Any idea how i can make this behaviour work for mobile browsers?


Solution

  • The error was that on some mobile devices that I was testing (not all!) has sometimes send 2 tab events (double tab).

    To fix that I have been added a delayTime and checked when the function got called last time.

    var buttonCallback = function() {
        if( timeout === null ) {
            //for old slow andoid devices
            if ((new Date().getTime() - delayTime) < 2200) 
                return;
            delayTime = new Date().getTime();
            log('show lines');
            timeout = setTimeout(buttonCallback, 3000);
        }
        // for fast devices to prevent the double tab error
        else if ( (new Date().getTime() - delayTime) > 1200 ) {
            clearTimeout(timeout);
            timeout = null;
            log('hide lines');
        }
    }