【发布时间】:2018-04-19 21:09:01
【问题描述】:
我正在递增一个计数器,从 0 开始,直到指定的端点并在特定的持续时间内。
在持续时间内调用一个函数,无限次来执行计数器的递增。
目标是在持续时间的确切结束时将计数器增加到端点。
根据端点和持续时间,不知道计数器增加多少。
我的问题是如何通过仅使用端点和持续时间作为已知变量来确定递增计数器的数字?
下面是一个代码示例来说明:
let duration = 2000; // two seconds
let endpoint = 1239;
let counter = 0;
let numberToIncrementBy = ''; // this is the unknown
function myFunc() {
if (counter >= endpoint) {
// reached the endpoint
return counter;
}
counter += numberToIncrementBy;
return counter;
}
更新:我在下面添加了这个问题背后的更多细节:
我正在使用progressbarjs 创建动画进度条。要使用它,您可以使用 ProgressBar.ShapeName() 创建一个新的 Shape 对象,并将容器元素作为它的第一个参数传递给它。您还可以将选项对象传递给它,您可以在其中定义持续时间属性。
duration = 2000; // duration variable from above
let circle = new ProgressBar.Circle('#the-container', { duration: duration });
创建 Shape 对象后,您可以对其调用 animate 方法,并传入一个 progress 变量 - 一个从 0 到 1 的数字 - 以指示动画应该停止的位置。
circle.animate(0.8); // 80% of progress bar
我为“解决”我的问题所做的工作 - 这仍然是一项正在进行的工作 - 是创建一个调用 ProgressBars animate 函数的函数,同时还调用一个自定义函数,该函数在动画到某个端点。
let invokeAnimation = function() {
let progress = 1400; // arbitary number
let endpoint = 2100; // also arbitrary but must be larger than progress variable
// manufacture a progress variable to pass to circle.animate() to determine - between 0 and 1 - where the animation should stop
let progressEnd = (progress / endpoint).toFixed(2); // 0.67
/* set up a function using setInterval to rapidly call a function */
let counter = 0;
// NOTE: this variable is critical in ensuring that the counter reaches the progress amount in the time it takes for the animation to complete
let incrementValue = Math.round(progress / duration * 100); // multiply by 100 and use math round to get a whole number
let outputStr = " of " + endpoint; // will be combined with progress/counter and output as a string alongside the progress bar in the UI
let intId = setInterval(frame, 50); // declare a handle to the setInterval function to be able to later CLEAR the interval when no longer needed
function frame() {
// the counter has reached its target
if (counter >= progress) {
// clear setInterval
clearInterval(intId);
// Output text
// NOTE: circle.setText() is a defined by the ProgressBarJS API and sets the output text of the Shape object
circle.setText(progress + outputStr );
return;
} else {
circle.setText(counter + outputStr);
counter += incrementValue;
}
}
这段代码的效果是可以定义progress 和endpoint 值,并且在一组duration 内,计数器将递增到progress 的值。这会创建与图形进度条或进度条同步的动态文本输出。
感谢@cybersam 和@NolanWalker 试图从上面回答我的错误问题。事实上,@NolanWalker 建议使用 setTimeout,再加上 W3School 网站上使用setInterval to create a dynamic progress bar 的这个例子的发现启发了我的结果。
请注意,上面的代码不考虑函数调用,在我原来的帖子中解释过,它被称为无限次。该函数是circle.animate() 方法的step function 的结果,用于创建动画。
最后,setInterval 函数的第二个参数是帧速率。在上面的代码中,我将其设置为 50 相当随意。我的代码没有将frame rate 纳入其结论中,我认为这是一个可以改进的领域(但我对我的代码的结果感到非常满意 - 并且足够懒惰 - 我会暂时保留它!)。
干杯!
【问题讨论】:
标签: javascript progress-bar counter increment duration