Reputation: 61
I have been working on writing a library of code for my future projects. One of the functions I've been working on is a pause function. So far I have no problem with the errors reporting that the script is running to long even on pauses as long as 10 seconds. This is to primarily keep malicious users busy, it works well when you set a very long time. I was wondering if there are any errors that I should look out for that I might face? Here's the code...
pause = function(a) {
var b = new Date().getTime();
e = false;
function wait() {
d=10;
for(i=0;i<d;i++) {
d++;
var c = new Date().getTime();
if(c-b>=a) {
e = true;
break;
}
if(d>1000000) {
break;
}
}
}
wait();
if(e==false) {
pause(a-(new Date().getTime()-b));
}};
Upvotes: 0
Views: 3055
Reputation: 707446
As I've said in my comments so far, trying to run semi-infinite loops in javascript is never a good idea.
Here are some of the issues to watch out for:
Essentially what you're trying to do is a denial-of-service attack on a user's browser. You may not like what they're doing to your web page, but attacking them back does not seem appropriate. Much better to just block access to your page in a browser-appropriate way rather than a browser-attacking way.
Suggestions:
If what you're really trying to do is just render your page unuseful in some circumstances (you still haven't explained why you're trying to do this or what condition triggers your desire to do this), then it might be better to just make the page unuseful or informative without trying to kill the browser. You could do that by:
Upvotes: 1
Reputation: 809
Javascript already has a way to do that. Use setTimeout() and pass it an anonymous function with the continuation of your operation. The second argument is the delay in milliseconds.
Example:
setTimeout(function(){ alert('hello'); }, 2000);
Upvotes: 0
Reputation: 993243
You never ever want to do this sort of thing in Javascript. As you have noticed, the browser will complain about your script taking too long. Furthermore, this will take much more energy than necessary which is important for mobile devices with limited battery capacity.
Instead, use the standard setTimeout()
function to run code at a later time.
Upvotes: 4