gpt4 book ai didi

Javascript 函数抛出错误

转载 作者:行者123 更新时间:2023-11-29 17:16:07 25 4
gpt4 key购买 nike

首先,我对 JavaScript 一点都不流利。我已经将这个函数拼凑在一起以提取一些统计数据并将它们作为 html 字符串应用到使用 JSON 的相关元素。有时有效,有时无效。

据我所知,该函数应该在执行任何操作之前等待 3 秒,然后每 2 秒一遍又一遍地重复该函数(正确吗?)。

var userGameStats = setTimeout(function () {
$.getJSON('/id/stats', function (data) {
// Pull the stats
var userWinningBets = data.winningBets,
userLosingBets = data.losingBets,
userTotalBets = data.totalBets,
userStreak = data.streak,
userBestStreak = data.bestStreak;

// Apply stats to elements
$('#stats_won span').text(userWinningBets);
$('#stats_lost span').text(userLosingBets);
$('#stats_total span').text(userTotalBets);
$('#stats_ratio span').text((userTotalBets > 0) ? ((userWinningBets / userTotalBets) * 100).toFixed(1) + '%' : "0%");
$('#stats_streakbest span').text(userBestStreak);
$('#stats_streak span').text(userStreak);
});

userGameStats();
setInterval(userGameStats, 2000);
}, 3000);

我收到此错误(在控制台中):

Uncaught TypeError: Property 'userGameStats' of object [object Object] is not a function
(anonymous function)

我该如何解决这个问题?有没有更好、更正确的方法来格式化语法?

最佳答案

在您的情况下,userGameStatssetTimeout() 返回的值,它是对创建的计时器(一个 int 值)的引用,这就是错误的原因.

应该是

var userGameStats = function () {
$.getJSON('/id/stats', function (data) {
// Pull the stats
var userWinningBets = data.winningBets,
userLosingBets = data.losingBets,
userTotalBets = data.totalBets,
userStreak = data.streak,
userBestStreak = data.bestStreak;

// Apply stats to elements
$('#stats_won span').text(userWinningBets);
$('#stats_lost span').text(userLosingBets);
$('#stats_total span').text(userTotalBets);
$('#stats_ratio span').text((userTotalBets > 0) ? ((userWinningBets / userTotalBets) * 100).toFixed(1) + '%' : "0%");
$('#stats_streakbest span').text(userBestStreak);
$('#stats_streak span').text(userStreak);
});
}

setTimeout(function(){
userGameStats();
setInterval(userGameStats, 2000);// once started repeat every 2 seconds
}, 3000); //first time wait for 3 seconds

关于Javascript 函数抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17675444/

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