JSFiddle - React, Tailwind, and code Playground

by ustamansangat

HTML

<p>Second click gets processed BEFORE the setTimeout(..,0) in the first click.
        <p/>
        <p>
            <input type='button' id='mybutton1' class='mybutton' onclick='clickHandler(this);' />
        </p>
    <p>Second click gets processed AFTER the setTimeout(..,0) in the first click.
        <p/>

        <p>
            <input type='button' id='mybutton2' class='mybutton' onclick='clickHandler(this);' />
        </p>
        <p>
            <input type='button' onclick='reset()' value='RESET' />
        </p>

JavaScript

function spinWait(MILLIS) {
    var end = Date.now() + MILLIS;
    console.log('Gonna wait ' + MILLIS + 'ms');
    while (Date.now() < end);
    console.log('Done waiting');
}

window.reset = function () {
    $('.mybutton').removeAttr('disabled');
    $('.mybutton').removeAttr('called');
    $('.mybutton').val('click TWICE');
}

window.clickHandler = function (target) {
    console.log(target);
    var el = $(target);
    var button1 = el.attr('id') === 'mybutton1';
    if (!el.attr('called')) {
        el.attr('called',true);
        if(button1) spinWait(1000);
        setTimeout(function () {
            el.val('FROM FIRST CLICK');
        }, 0);
        if(!button1) spinWait(1000);
    } else {
        el.attr('disabled', 'disabled');
        el.val('FROM SECOND CLICK');
    }
};

window.reset();