I have a simple question: I am using this function for getting prices from CryptoCompare and now I would like set interval for refreshing data without refreshing page. So I have tried this code:
<script>
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
setInterval(getData, 3000);
$(function() {
getData();
});
</script>
But it is not working for me. Can you help me, please?
You have some convoluted code. I think what you are intending is for your fetch to be called every 3 seconds.
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
This defines you get function. You have a sample call as
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
You are using setInterval incorrectly though, see https://www.w3schools.com/jsref/met_win_setinterval.asp
You have 2 lines here
setInterval(getData, 3000);
$(function() { getData(); });
This is incorrect, getData is only a name for your function. The setInterval function should take your anonymous function with defined parameters like
setInterval($(function() {
getData('dash', 'https://min-api.cryptocompare.com/data/price?fsym=DASH&tsyms=USD');
}), 3000);
Per your JS fiddle, this works for me (removed jquery function and replaced with regular js lambda)
function getData(prefix, url) {
$.getJSON(url, function(data) {
$.each(data, function(key, val) {
$('.' + prefix + '-' + key.toLowerCase()).html(val);
});
});
}
setInterval(function() {
getData('btc', 'https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD');
}, 3000);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.