JS: Prevent Unresponsive Script Warnings

无人久伴 提交于 2020-01-05 03:08:38

问题


I'm working on a JS project that generates a pattern from a noise algorithm. I'm generating multiple octaves of noise to get the result I want which ends up being around 7,000,000 values. As you can imagine, I'm getting an unresponsive script error from this.

  • Is there a way to suppress this message in modern browsers? In this instance, the script is doing it's expected behavior—generating noise—and it is expected that it will take a little while.
  • Would it be faster to generate noise with a server-side language and pass it back using AJAX or something?

Thanks!


回答1:


You could use webworkers, which would look something like:

if (window.Worker) {
    // load web worker
    var thread = new Worker("webworker.js");
    // message received from web worker
    thread.onmessage = function(e) {
        var noise = e.data;
        //do something
    }
    // start web worker
    thread.postMessage(7000000);

}
else {
    output.textContent = "Web Workers are not supported in your browser";
}

webworker.js:

self.onmessage = function(e) {
    var r = e.data;
    while (r-- > 0) {
      //generate some noise
    }
    self.postMessage(noise);

};

If you don't want to use webworkers, for each "step" of your generation process, wrap it in a setTimeout with a small delay. These delays will give the browser time do other stuff and stay responsive.



来源:https://stackoverflow.com/questions/29134753/js-prevent-unresponsive-script-warnings

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