setInterval +随机数 [英] setInterval + Random Number
问题描述
我正在尝试创建一个每5秒生成一个数字的函数,但是当我使用这些函数时存在一个问题,因为我想对此数字使用animateNumber()
函数.我收到此错误消息:
I'm trying to create a function which generates a number every 5 seconds but there is one problem when I use these function because I want to have animateNumber()
function on this number. I'm getting this error message:
未捕获的ReferenceError:x未定义
Uncaught ReferenceError: x is not defined
循环正在工作,只是不知道如何解决此错误.谢谢您的帮助
The loop is working just don't know how to fix this error. Thanks for any help
function myInterval() {
var x = Math.round(Math.random() * 5000) + 1;
}
var timeoutId = setTimeout(ref, 100);
var intervalId = setInterval(ref, 5000);
var intervalId = setInterval(myInterval, 5000);
// ANIMATED NUMBER
function ref() {
$("#budget-left").animateNumbers(x);
}
推荐答案
x
变量是在myInterval
函数中定义的,因此在ref()
内部是不可访问的-因此出错.您需要提高范围:
The x
variable is defined in the myInterval
function, so is inaccessible inside ref()
- hence the error. You need to raise it's scope:
var x = 0;
function myInterval() {
x = Math.round(Math.random() * 5000) + 1;
}
var timeoutId = setTimeout(ref, 100);
var intervalId = setInterval(ref, 5000);
var intervalId = setInterval(myInterval, 5000);
// ANIMATED NUMBER
function ref() {
$("#budget-left").animateNumbers(x);
}
还请注意,如果您有一个计时器,则调用一个函数既生成数字又显示数字,则逻辑将更有意义.试试这个:
Also note that the logic would make more sense if you had a single timer, calling a single function which both generates the number and then displays it. Try this:
var intervalId = setInterval(function() {
var randomNumber = Math.round(Math.random() * 5000) + 1;
$("#budget-left").animateNumbers(randomNumber);
}, 5000);
这篇关于setInterval +随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!