我试图实现一个setInterval()方法,但我不确定在哪里放置它。基本上,我希望这整个JavaScript脚本每分钟运行一次。我想我要添加的代码是我在下面添加的一行代码,但我不知道确切的位置,并且我不知道第一个参数应该是什么(虽然我知道它应该是我想要调用的函数的名称。
setInterval(myTimer, 60000);
这里是完整的代码:
<!DOCTYPE html>
<html>
<head>
<title>Ethereum Tracker</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
let myData = "";
let dataTest = "";
$.get("https://api.coinmarketcap.com/v1/ticker/ethereum/", function(data, status){
myData = data[0];
document.getElementById("p1").innerHTML = (myData.price_usd);
});
});
</script>
</head>
<body>
<p id="p1"></p>
<p id="p2"></p>
<script>
var d = new Date();
document.getElementById("p2").innerHTML = 'Last updated: ' + d.toLocaleTimeString();
</script>
</body>
</html>
答案 0 :(得分:1)
你需要做这样的事情
<!DOCTYPE html>
<html>
<head>
<title>Ethereum Tracker</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function update(){
let myData = "";
let dataTest = "";
$.get("https://api.coinmarketcap.com/v1/ticker/ethereum/", function(data, status){
myData = data[0];
$("#p1").html(myData.price_usd);
var d = new Date();
$("#p2").html('Last updated: ' + d.toLocaleTimeString());
});
}
$(document).ready(function(){
// run every minute
setInterval(update, 60000);
// run immediately on load
update();
});
</script>
</head>
<body>
<p id="p1"></p>
<p id="p2"></p>
</body>
</html>
答案 1 :(得分:0)
假设您想每分钟更新价格,它应该如下所示:
$(document).ready(function(){
setInterval(updatePrice,60000);
});
function updatePrice(){
let myData = "";
let dataTest = "";
$.get("https://api.coinmarketcap.com/v1/ticker/ethereum/",
function(data, status){
myData = data[0];
document.getElementById("p1").innerHTML =(myData.price_usd);
});
}