Web SQL Database + Javascript

I'm trying to figure it out, but I can't seem on my own ...
I play with Web SQL databases and I cannot get the loop to work with it.
I use:

for (var i=0; i<=numberofArticles-1; i++){ db.transaction(function (tx) { tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)', [i]); }); }; 

And I get only 5 .. I do not get incremental i values.
Can anyone suggest what I'm doing wrong, and what should I think about?

+7
source share
2 answers

It seems that the function is asynchronous and that by the time tx.executeSql loop had completed the loop and i was changed several times.

You can solve this problem with closing.

 for (var i=0; i<=numberofArticles-1; i++){ function (value) { db.transaction(function (tx) { tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)', [value]); }); }(i); // <-- CALL the function }; 
+6
source

Do it the other way around:

 <script> numberofArticles = 5; db = openDatabase("websql", "0.1", "web-sql testing", 10000); db.transaction(function(tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, articleID int)'); }); db.transaction(function (tx) { for (var i=0; i<=numberofArticles-1; i++){ tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)', [i]); }; }); </script> 

And an alternative, the correct closed-loop path, which in this case is not needed

  for (var i=0; i<=numberofArticles-1; i++){ (function(i) { db.transaction(function (tx) { tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)', [i]); }); })(i); }; 
+11
source

All Articles