gpt4 book ai didi

javascript - 每秒从 API 更新数据

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:28 24 4
gpt4 key购买 nike

我目前正在为一个使用 Spotify API 的学校项目工作。现在,我已经收到了某人正在收听的当前歌曲。

但问题是,只有在刷新或打开站点后才会收到该信息,但我希望它每秒保持刷新(而不刷新整个页面),以便它与监听器保持同步。这里有人对我如何做到这一点有任何想法吗?

这是我正在使用的 AJAX 请求(我不确定它是否有用或有什么用)

$.ajax({
url: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
userInfoPlaceholder.innerHTML = userInfoTemplate(response);
console.log(response);
$('#login').hide();
$('#loggedin').show();
}
});

如果我需要发布任何其他代码以提供帮助,请告诉我!

最佳答案

您可以使用 setTimeout 或 setInterval 来实现。

区别在于 setInterval 在指定的时间间隔一次又一次执行给定函数(直到调用 clearInterval() 函数); setTimeout 在指定的时间间隔之后一次执行给定函数。

在您完成必要的响应过程之后。您可以在函数末尾递归调用 makerequest() 函数。该行包含注释,提供 makerequest() 函数,将在 10 秒后再次调用。

function makerequest() {
$.ajax({
url: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
userInfoPlaceholder.innerHTML = userInfoTemplate(response);
console.log(response);
$('#login').hide();
$('#loggedin').show();
//process with the response and other stuffs
setTimeout(makerequest, 10000); //recursive call
}
});

}

关于javascript - 每秒从 API 更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52852478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com