Javascript loop freezes browser and doesn't see changes before loop

I have a simple javascript loop, as you saw below:

function runCode() {
    $("#sample-span").removeAttr("style");
    for (var i = 0; i < 100000; i++) {
        console.log(new Date());
    }
    $("#sample-span").toggleClass("colorized");
}

This is the span class switch on the page as shown below:

<span id="sample-span" style="color: orange;">Sample Text</span>
<input type="button" value="click to run" onclick="runCode()" />

<style>
span {
    color: blue;
}
.colorized {
    color: red;
}
</style>

The problem is that when the loop starts, the page freezes and cannot see that the color of the range changes.

How can I solve this problem?

jsfiddle link

UPDATE

Dear, console.log(new Date());this is just a sample, you assume that heavy javascript projects work here.

+4
source share
4 answers

You should add a little delay after the color change before starting the heavy process:

function runCode() {
  $("#sample-span").toggleClass("colorized");
  setTimeout(runTask,10)
}

function runTask(){
    for (var i = 0; i < 100000; i++) {
    console.log(new Date());
  }
  $("#sample-span").toggleClass("colorized");
}

Jsfiddle

+3
source

, javascript DOM. , , , , .

, , :

function runCode() {
    $("#sample-span").toggleClass("colorized");
    // allows the first toggle to execute and sends the loop and the second
    // toggle to the end of the task queue
    setTimeout(function() {
        for (var i = 0; i < 5000; i++) {
            console.log(new Date());
        }
        $("#sample-span").toggleClass("colorized");
    }, 0);
}

, , .

+2

? , , , , , setTimeout.

  $("#sample-span").toggleClass("colorized");

  setTimeout(function() { $("#sample-span").toggleClass("colorized") }, 1000);
0

, . , , : function runCode() { $("#sample-span").toggleClass("colorized"); for (var i = 0; i < 100000; i++) { console.log(new Date()); } }

-2

Source: https://habr.com/ru/post/1686476/


All Articles