我有一个网站,用户可以出售文章,这将保存到ethereum区块链。在该网站上,顶部看起来如下:
<div id="recentArticles"></div>合同包括以下内容(我只写了重要的部分):
struct Article {
address seller;
uint bid;
uint bidder;
}
Article[] articles;
function getArticle(uint _id) returns(address seller, uint bid, uint bidder){
return(articles[_id].seller,articles[_id].bid,articles[_id].bidder);
}
function getArticlesAmount() returns(uint amount) {
return articles.length;
}javascript代码:
function initiateArticles() {
contract.getArticleAmount({from: web3.eth.accounts[0]},function(error, result)
{
if(!error)
{
i = 0;
while(i <= result) {
getArticle(i)
i++;
}
}
else {
console.log(error);
}
});
}
function getArticle(id) {
contract.getArticle(id, {from: web3.eth.accounts[0]},function(error, result)
{
if(!error)
{
document.getElementById("recentArticles").innerHTML = document.getElementById("recentArticles").innerHTML + result[0] + result[1]...;
## This is not the finished code. Here I need help.
}
else {
console.log(error);
}
});
}
document.onload = initiateArticles();现在我想要的是:当用户访问该网站时,它应该调用合同来加载最近的10篇文章,并将它们显示在div "recentArticles“中。这很简单,我成功地做到了。但现在我需要帮助了。
我希望,每隔一秒,就会有另一个电话呼叫合同,以获取被称为“物品”的10种产品的最新值。
用户来到这个网站并查看它。它加载了最后10篇文章。有人竞拍一篇文章。div中的文章现在应该显示新的出价。
对每一篇文章进行每秒调用的函数的最佳方法是什么?我需要10个“更新者/点票”。
非常感谢你的回答。
发布于 2018-06-13 14:02:31
这可以在javascript中完成,可以使用setInterval()或setTimeout():
如果您不关心timer中的代码是否比间隔时间长,请使用setInterval():
setInterval(function_that_checks_the_price_for_a_product, delay)它一次又一次地激发作为第一个参数传入的函数。
更好的方法是,在使用setTimeout和self-executing anonymous函数的同时使用:
(function(){
// do some stuff
setTimeout(arguments.callee, 15000); //execute itself every 15 seconds - the avg block time on ethereum
})();这保证了下一个调用不会在代码执行之前进行。在本例中,我使用arguments.callee作为函数引用。这是给函数命名并在setTimeout中调用它的更好方法,因为ecmascript 5中不推荐使用arguments.callee。
使用setInterval(),您的initiateArticles()函数如下所示:
function initiateArticles() {
contract.getArticleAmount({from: web3.eth.accounts[0]},function(error, result)
{
if(!error)
{
i = 0;
while(i <= result) {
//need a wrapper anonymous function so we can send the i param to getArticle()
setInterval(getArticle.bind({articleId: i}), 15000);
i++;
}
}
else {
console.log(error);
}
});
}并将函数getArticle()更改为:
function getArticle() {
const id = this.articleId;
contract.getArticle(id, {from: web3.eth.accounts[0]},function(error, result)
{
if(!error)
{
document.getElementById("recentArticles").innerHTML = document.getElementById("recentArticles").innerHTML + result[0] + result[1]...;
## This is not the finished code. Here I need help.
}
else {
console.log(error);
}
});
}https://ethereum.stackexchange.com/questions/51123
复制相似问题