0

That I try to do : Click on a button, sleep, change the label to "Run", sleep , change the label "OK"

I have a button ( #runajax) with click event function. I have a table with label:

<table class="table table-bordered">
    <tbody>
        <tr>
            <td >Status Global </td>
            <td align="center"><label id="Status">FieldToUpdate</label></td>
        </tr>
    </tbody>
</table>

Javascript :

function setStatusRun(runType )
{
    $("#Status" + runType).text("running....");
}

function setStatusOK(runType )
{
    $("#Status" + runType).text("OK");
}

$(document).ready(function () {
    // initialize the viewer
    $('#runajax').click(function (event) {
        resetStatus();
        setStatusRun("");
        sleep(3000);
        setStatusOK("");
        sleep(3000);
        event.preventDefault();     
    });
});

But I can see only the final update, not the intermediate value of the label.

Someone can help me ?

krlzlx
  • 5,752
  • 14
  • 47
  • 55
user5023028
  • 35
  • 1
  • 6
  • What is `sleep()` method??? – A. Wolff Nov 06 '15 at 12:51
  • function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds) { break; } } } – user5023028 Nov 06 '15 at 12:53
  • Sleep function it's just to simulate some jobs – user5023028 Nov 06 '15 at 12:54
  • Javascript is single thread language, you are blocking the UI which has no time to update. If you want to simulate an ajax call, which is btw async, then you can use `setTimeout()` instead – A. Wolff Nov 06 '15 at 13:06

1 Answers1

0

I have done some research around and figure out using setTimeout is a better way than sleep

setTimeout(function(), delay)

This is my code on fiddle:

http://jsfiddle.net/mankinchi/0nubjp88/

I have tried this at first:

setTimeout(function() {
        setStatus("run");
    },3000);
setTimeout(function() {
        setStatus("stop");
    },3000);

but got the same problem as you have: showing the last one, not the middle).

I have some rough time trying to understand the reason why. Then I change the later one to 6000 and I got the result. I believe both of the setTimeout run async (doesn't wait for the code to complete to do others). Have a look here for more details:

Asynchronous vs synchronous execution, what does it really mean?

Community
  • 1
  • 1
Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37
  • Maybe I wasn't clear but my issue is NOT about the sleep or timeout. I just use it to simulate some jobs, nothing more. My issue is on the update of the label. I don't have the "middle" update. – user5023028 Nov 06 '15 at 13:23
  • @user5023028 read again. I also mention the reason why I have the same result as yours – Tree Nguyen Nov 06 '15 at 13:24