U
U
un1t2014-09-05 15:40:09
phonegap
un1t, 2014-09-05 15:40:09

Phonegap - why is the css class switching slowly?

I made a flashlight as a "hello world".
There is a simple button:

<div id="switch-button" class="switch-button"></div>

Styles:
.switch-button {
    width: 100px;
    height: 100px;
    background-color: blue;
    color: #fff;
    text-align: center;
    vertical-align: middle;
    margin: 100px auto;
}

.switch-button__on {
    background-color: red;
}

On click, add the "switch-button__on" class to change the color of the button.
var btn = document.getElementById('switch-button')
btn.onclick = function () {
    if (btn.classList.contains('switch-button__on')) {
        btn.classList.remove('switch-button__on');
        window.plugins.flashlight.switchOff();
    } else {
        btn.classList.add('switch-button__on');
        window.plugins.flashlight.switchOn();
    }
}

The surprise was that the button color switching is somehow noticeably slow, the flashlight turns on noticeably earlier than the button changes color, although the call order is reversed.
Why does it go like this? How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-09-05
Protko @Fesor

updates.html5rocks.com/2013/12/300ms-tap-delay-gon...
update:
Another reason could be that calling window.plugins.flashlight.* blocks the thread, meaning the plugin runs on the same thread as webview and reflow/repaint does not occur until window.plugins.flashlight is released.
Try like this:

var btn = document.getElementById('switch-button')
btn.onclick = function () {
    if (btn.classList.contains('switch-button__on')) {
        btn.classList.remove('switch-button__on');
        setTimeout(function () {
             window.plugins.flashlight.switchOff();
        }, 0);
        window.plugins.flashlight.switchOff();
    } else {
        btn.classList.add('switch-button__on');
        setTimeout(function () {
            window.plugins.flashlight.switchOn();
        }, 0);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question