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