问题
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