Pausing a javascript database query until setTimeout has finished
I have a problem. I am querying a database and going through each result from the DB. The DB has 2 columns Name and Time. Now what i want the javascript to do is display that Name for the amount of time that is held in the database. I've tried to do this using setTimeout().
after SELECTing from DB:
function (transaction, result) {
for (var i = 0; i < result.rows.length; i++)开发者_运维百科 {
var row = result.rows.item(i);
$('div.box').html(row.name);
var countdown;
var countdown_number;
countdown_init();
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
if (countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
if (countdown_number > 0) {
countdown = setTimeout('countdown_trigger()', row.time);
}
}
}
}
}
Now, my problem here is, i believe, to do with threading in javascript (but i may be wrong). When the countdown starts, it does not pause the execution of the loop, but rather starts the countdown on a new thread and carries on in the loop bringing up the next DB entry and crashing out with all kinds of errors.
So how do i get around this? I have thought about adding flags.. but i'm not sure how this could work. I have a feeling (i hope) there is a straightforward answer to this but not sure what it is.
try
function (transaction, result) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
$('div.box').html(row.name);
var countdown;
var countdown_number;
countdown_init();
function countdown_init() {
countdown_number = 11;
countdown_trigger();
}
function countdown_trigger() {
if (countdown_number > 0) {
countdown_number--;
document.getElementById('countdown_text').innerHTML = countdown_number;
if (countdown_number > 0) {
countdown = setTimeout(function(){countdown_trigger();}, row.time);
}
}
}
}
}
精彩评论