javascript loop freezes browser and can't see change before loop

给你一囗甜甜゛ 提交于 2019-12-01 17:34:08

You have to add a small delay after changing the color before running 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

The problem with your code is that the javascript task queue executes all available code in your function before performing DOM manipulation. Meaning that the class toggle calls are registered, the loop is executed, then the toggles are executed successively so you cannot see the color change.

What you need to do is send the second part of your function to the end of the task queue like follows :

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);
}

I have reduced the number of iteration to reduce the browser lock, you can still see the color change still.

What are you trying to actually do? If you want the text to be shown as red and then toggle back after a specified time what you're really looking for is a setTimeout.

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

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

It's because you are toggling class twice on a button click. If you want to change color of the span when it finishes then write: function runCode() { $("#sample-span").toggleClass("colorized"); for (var i = 0; i < 100000; i++) { console.log(new Date()); } }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!