Reputation: 540
I am wondering if there's some work-around for my "problem".
I play a game which i customize with Javascript/jQuery through Greasemonkey/Firefox.
There are plenty of scripts which modifies the DOM and some input values. On my custom script i use an ajax call which takes around 15-20 seconds to complete, but by that time the page is modified and so i got here.
I suppose i have to somehow stop everything, all javascripts, freeze the page completely until my ajax finishes, but keep in mind that i can't control / modify all scripts on the page. From my experience .. everything is possible, am i wrong now ? .. Thank you.
Upvotes: 1
Views: 4950
Reputation: 42054
Sorry even if it's been a while but the situation You posted caught my attention more than I imagined. So I checked a lot of possibilities and at the end i suggest the following one:
var _setTimeout;
var _clearTimeout;
var _setInterval;
var _clearInterval;
var _pauseOn;
_setTimeout = window.setTimeout;
_clearTimeout = window.clearTimeout;
_setInterval = window.setInterval;
_clearInterval = window.clearInterval;
_pauseOn = false;
window.setTimeout = function(code, delay) {
return _setTimeout(function () {
if (_pauseOn == true) {
return;
}
code();
}, delay);
};
window.clearTimeout = function(intervalId) {
if (_pauseOn == true) {
return;
}
_clearTimeout(intervalId);
};
window.setInterval = function(code, delay) {
return _setInterval(function () {
if (_pauseOn == true) {
return;
}
code();
}, delay);
};
window.clearInterval = function(intervalId) {
if (_pauseOn == true) {
return;
}
_clearInterval(intervalId);
};
function pauseTimer() {
_pauseOn = true;
}
function resumeTimer() {
_pauseOn = false;
}
/*
* To test:
* shift + p --> pause game
* shift + r --> resume game
*/
$(window).keypress(function(event) {
if (event.shiftKey) {
switch (String.fromCharCode(event.which).toLowerCase()) {
case 'p':
event.preventDefault();
pauseTimer();
break;
case 'r':
event.preventDefault();
resumeTimer();
break;
}
}
});
I hope that's could be apreciated.
Ps. Looking and testing with the tetris.js (Copyright (c) 2006 Franck Marcia) You can see in the original source code that the pause and resume methods of the game are not simply implemented as stopping timers, but it's enough to reach the solution You need!
Upvotes: 1
Reputation: 7207
I don't know if it's the best or the most efficient way to do it but you can create a window.pauseAll
variable and set it as false:
window.pauseAll=false;
and then when the ajax is being called set it to true:
window.pauseAll=true;
$.ajax({...});
then for every event check if pauseAll
is true, if not then do the script, else don't:
$('#element').click(function(){
if(!window.pauseAll){
//do the stuff you want
}
});
then after the ajax call is completed, set it to false
again:
$.ajax().done(function(){
window.pauseAll=false;
});
Upvotes: 0