Prevent recursive function locking the browser - javascript

I have a recursive function which is locking my browser while running.
While this function is running all my jquery commands are locked waiting for the function end.
What should I do to make this function asynchronous?
This function runs on document.ready
function SearchTrip() {
$.post("/extensions/searchtrip", {
from: $("#from").val(),
to: $("#to").val(),
ddate: $("#ddate").val()
},
function (mReturn) {
if (mReturn.fTotalAmount != '0,00') {
var sAirline = '';
if (mReturn.Airline)
sAirline = ' pela ' + mReturn.Airline;
$("#buscandoPassagens").hide();
} else if (SearchTripAmount < 5) {
SearchTripAmount++;
setTimeout(function () {
SearchTrip();
}, 500);
} else {
$("#pNaoEncontrada").show();
}
},
"json");
}

If you want to run it asynchronously just wrap everything with setTimeout:
function SearchTrip(){
setTimeout( function() {
//this is your $.post i just deleted 'content' to make answer easier to read
$.post();
}, 0);
}

Related

setTimeout() not working in return value

I have add setTimeout but it's not working. I want to show question after 5 sec of the end of the sound.
self.getQuestionText = function() {
startSound('levelq', false);
setTimeout(function() {
return self.questions[self.level() - 1].question;}, 5000);
}
setTimeout() in asynchronous and returns the value in the callback function. Change the structure of your js.
Instead of:
self.getQuestionText = function () {
startSound('levelq', false);
setTimeout(function () {
return self.questions[self.level() - 1].question;
}, 5000);
}
// The rest of the code
Use callback structure:
self.getQuestionText = function () {
startSound('levelq', false);
setTimeout(function () {
self.getQuestionText = self.questions[self.level() - 1].question;
// The rest of the code
}, 5000);
}

CasperJS: WaitFor timeout function to do rescroll?

I met some problem when I use CasperJS to scrape a website. The website is dynamically loaded like Twitter, so I want to do infinite scroll,
and thanks to #Artjom B. I found you code to do this.
var tryAndScroll = function (casper) {
try {
casper.echo('SCROLL!!');
casper.scrollToBottom();
if (casper.exists('div.loading')) {
var curItems = casper.evaluate(getCurrentInfosNum);
casper.echo(curItems);
casper.waitFor(function check() {
return curItems != casper.evaluate(getCurrentInfosNum);
}, function then() {
casper.wait(800);
tryAndScroll(casper);
}, function onTimeout() {
casper.emit('scroll.timeout',curItems);
}, 15000);
} else {
casper.echo("No more items");
return true;
}
} catch (err) {
casper.echo(err);
}
} //casper.tryAndScroll
And now, I want to continue to scroll many times when the timeout function invoked so I create my own event listener,‘scroll.timeout’.
var SRCOLL_NUM = 0;
var PreOfLoaded = 0;
casper.on('scroll.timeout', function (NumOfLoaded) {
if (SRCOLL_NUM <= 4) {
if (PreOfLoaded == NumOfLoaded)
SRCOLL_NUM++;
this.echo("Scroll Timeout,reScroll");
PreOfLoaded = NumOfLoaded;
tryAndScroll(casper);
} else {
this.echo("Scroll Timeout,reScroll times maximum");
SRCOLL_NUM = 0;
PreOfLoaded = 0;
}
});
However, when scroll timeout occurred, it printed Scroll Timeout,reScroll on the console. Then it skips tryAndScroll() and go to the next step in the main function. I want to continue to next step after retry scroll many times. What should I do?
I found CasperJS author illustrate :Automatic retry when open fails
var casper = require('casper').create();
casper.tryOpen = function(url, then) {
return this.then(function() {
this.open(url);
this.waitFor(function testStatus() {
return this.getCurrentHTTPStatus === 200;
}, then, function onFail() {
console.log('failed, retrying');
this.tryOpen(url);
}, 2000);
});
};
casper.start().tryOpen('http://failing.url.com/foo.bar', function() {
this.echo('wow, it worked, wtf');
}).run();
unfortunately, it doesn't work for me.
Try this
return this.currentHTTPStatus === 200;
I tested with the newest version of casperjs 1.1.1, it's working fine

setInterval doesn't get cleared, function keeps getting executed

I have the following function:
function monitorClimate() {
var sensorReadingInterval;
function startClimateMonitoring(interval) {
sensorReadingInterval = setInterval(function() {
io.emit('sensorReading', {
temperature: sensor.getTemp() + 'C',
humidity: sensor.getHumidity() + '%'
});
}, interval);
console.log('Climate control started!');
}
function stopClimateMonitoring() {
clearInterval(sensorReadingInterval);
console.log('Climate control stopped!');
}
return {
start: startClimateMonitoring,
stop: stopClimateMonitoring
};
}
I am watching a button for changes of state like this:
button.watch(function(err, value) {
led.writeSync(value);
if (value == 1) {
monitorClimate().start(1000);
} else {
monitorClimate().stop();
}
});
The problem is that even after the monitorClimate().stop() call, setInterval keeps getting triggered, thus SocketIO keeps on emitting the sensorReading event.
What am I doing wrong here?
Every time you call monitorClimate() you are creating a new set of functions so monitorClimate().start() and monitorClimate().stop() are not working on the same interval. Try something like:
var monitor = monitorClimate();
button.watch(function(err, value) {
led.writeSync(value);
if (value == 1) {
monitor.start(1000);
} else {
monitor.stop();
}
});

setTimeout keeps firing, how to make it fire only once?

I am making a simple chat, it works in different browsers but setTimeout keeps firing, and I want it to fire only once as it is pointless to keep firing and I believe also it would cause more stress on the server.
This is the function which is called from somewhere else:
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
setTimeout("chat_load();", 1000);
});
}
I tried something like the following but it just keeps on firing. Also, the function is supposed to fire only when a certain button is clicked, which happens only once every so often.
var c = 0;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
c++;
if (c == 3) {
clearTimeout(t);
}
});
}
I think you want something like this:
var c = 0, t;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
clearTimeout(t);
t = setTimeout(chat_load, 1000);
if (++c === 3) {
clearTimeout(t);
c=0;
}
});
}
You can't change variables in a asynchronous function
c++; wont work
maybe you should do this
function addCount() {
c++;
}
and change c++ to addCount();
so this
var c = 0;
function addCount() {
c++;
}
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
addCount();
if (c == 3) {
clearTimeout(t);
}
});
}

Why doesn't the clearInterval() works?

I'm new to JavaScript and I'm having problems with this script.
it's part of a web game and the script is suppose to refresh the page until the player wins or loses.
for some reason it doesn't stop refreshing, I put an alert function to check if the functions works, and i get the alerts but it's still continue refreshing the page.
what am i doing wrong?
var t;
$(document).ready(function () {
intervals();
});
function intervals() {
t = self.setInterval('refreshData()', 10000);
}
function youWin() {
var f = $('#status:contains("YOU ARE THE WINNER!")');
if (f.length > 0) {
alert("YOU ARE THE WINNER!");
t = clearInterval(t);
}
}
function youlose() {
var f = $('#status:contains("You lost!")');
if (f.length > 0) {
alert("You lost!");
t = clearInterval(t);
}
}
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame');
youWin();
youlose();
}
You need to fix the reference to self and fix the .load() call.
.load() is asynchronous so it does not complete before you call youWin() and youLose() right after it. You need a completion function so you can check winning or losing after the .load() completes successfully.
refreshData() should be structured like this:
function refreshData() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}
You also should change this:
t= self.setInterval('refreshData()',10000);
to this:
t = window.setInterval(refreshData, 10000);
I don't see that self was even defined so that could have also been causing your problem and you should use the function reference directly rather than put in a string.
And, as a cleanup issue, you should change both occurences of this:
t = clearInterval(t);
to this:
clearInterval(t);
Here's a cleaned up version of the code that also eliminates global variables and unnecessary function definitions:
$(document).ready(function() {
var t = window.setInterval(function() {
$('#ajaxGame').load('RefreshCurrentPlayerServlet #ajaxGame', function() {
youWin();
youlose();
});
}, 10000);
function youWin() {
if ($('#status:contains("YOU ARE THE WINNER!")').length) {
alert("YOU ARE THE WINNER!");
clearInterval(t);
}
}
function youlose() {
if ($('#status:contains("You lost!")').length) {
alert("You lost!");
clearInterval(t);
}
}
});

Categories

Resources