简体   繁体   中英

Can I put impose a time limit on JavaScript (e.g., using an iframe)?

I'd like to run some external JavaScript with a time restriction, so that if it takes more than N seconds it will be stopped.

Some browsers, eg Firefox, already do this with a dialog that asks if you want to allow a script to keep running. However, I'm looking for a bit more:

  • I want to set my own time limit rather than use the browser's default (eg, I believe Chrome's is much longer than Firefox's).
  • I want to be able to do this on a per-script basis, not per-page. One page may contain multiple scripts that I want to restrict in this way (hence my idea to use <iframe> elements).

I was thinking it would be very convenient if there were simply an attribute I could attach to an <iframe> —eg, something like js-time-limit="5000" (I just made that up)—but I haven't been able to find anything like that.

Is this possible? To put a configurable time limit on JavaScript execution in a browser?

If the iframe is doing computation work and doesn't need to access the DOM, then use web workers: https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers

Here is also a library that can abstract away the hard parts for you! http://adambom.github.io/parallel.js

Important parts:

Dedicated Web Workers provide a simple means for web content to run scripts in background threads.

If you need to immediately terminate a running worker, you can do so by calling the worker's terminate() method: myWorker.terminate();

Browser compatibility

Chrome  Firefox (Gecko)  Internet Explorer  Opera  Safari (WebKit)
   3        3.5 (1.9.1)          10         10.60        4

For posterity: my original goal was to allow users of a website to submit JS code and run it in the background with a time limit so that, eg, infinite loops don't wreak havoc on the CPU.

I created a library called Lemming.js using the approach Joe suggested . You use it like this:

var lemming = new Lemming('code to eval');

lemming.onTimeout(function() {
  alert('Timed out!');
});

lemming.onResult(function(result) {
  alert('Result: ' + result);
});

lemming.run({ timeout: 5000 });

You can check out the GitHub repo for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM