0
这是一个简单的vanilla JS脚本,连接到CoinMarketCap.com ticker API。Xhr:API Cryptocurrency价格警报脚本返回错误和重复值
它应该做的:
1)检索硬币数据,将其存储在一个对象
2)等待的时间x量(三分钟,在这种情况下)
3 )重复1),以获取最新的数据
4)比较近期的数据和以前的数据
5)硬币的价值有所回升,console.log
警报
6)重复上述过程
是什么呢: 两个对象(firstValue
和secondValue
)是重复的。此外,重新开始时(再次调用main()
函数),这两个对象的内容无法上移,并显示以前的值。
// Variables
// Set first recorded value
var firstValue;
// Set second value (most recent)
var secondValue;
// Get the obj from CoinMarketCap API
function getCoinValues() {
var requestURL ="https://api.coinmarketcap.com/v1/ticker/?limit=10";
var request = new XMLHttpRequest();
request.open("GET", requestURL);
request.send();
// When loaded assign to obj variable and return it
request.onload = function getUsdValues() {
// Save data to the 'obj' object
obj = JSON.parse(request.response);
console.log("Retrieved coin data");
};
return obj;
}
// Wait
function wait(ms){
console.log("Waiting.")
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
// Compare two objects
function comparePrices (obj1, obj2) {
// Take price from one array, compare to the other
for (var i = 0; i < obj1.length; i++) {
// console.log(JSON.stringify(obj2[i].id) + " OLD:" + obj1[i].price_usd + "NEW:" + obj2[i].price_usd)
if (obj2[i].price_usd > obj1[i].price_usd) {
console.log(JSON.stringify(obj2[i].id) + " has increased!");
console.log("From $" + obj1[i].price_usd + " to $" + obj2[i].price_usd);
}
}
}
// Main function //
function main() {
// Get 1st coin values
console.log("Getting first values");
firstValue = getCoinValues();
// Wait
console.log("Waiting")
wait(30000);
// Retrieve new values
console.log("Getting second values")
secondValue = getCoinValues();
// Compare two sets of values
console.log("About to compare prices")
comparePrices(firstValue, secondValue);
console.log("Prices compared")
// Do it all again
// "Emptying" the variables
firstValue = null
secondValue = null
// Starting the main loop
main();
}
main();
为什么不firstValue
和secondValue
显示不同的结果,即使价格已经有效地在股票变化?
请原谅任何不当使用的技术术语以及整体编码的新手。
这太棒了!谢谢你的彻底,@亚历克斯!我正在浏览你的代码,试图找出我所有的(无数)错误。 – user2331291
接受!再次感谢你的帮助。 – user2331291