jQuery进度计时器栏

jQuery progress timer bar

本文关键字:计时器 jQuery      更新时间:2023-09-26

我在jQuery中有一个进度计时器栏-下面是一个例子http://jsfiddle.net/6h74c/

如果我有以毫秒为单位的时间值(600000=10分钟,300000=5分钟等),我如何使条形图在这段时间内递增?

在jsfiddle链接中,我试图将进度条设置为增加835000ms。

然而,setTimeout()决定了条形图增加的频率,它也基于宽度百分比,这似乎不准确——我应该采取不同的做法吗?

function updateProgress(percentage) {
    $('#pbar_innerdiv').css("width", percentage + "%"); // probably not ideal
    $('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
    perc++;
    updateProgress(perc);
    if(perc < 835000) {
        timer = setTimeout(animateUpdate, 50); // probably not ideal either?
    }
}

Fiddle示例

我会做一些类似的事情:

var start = new Date();
var maxTime = 835000;
var timeoutVal = Math.floor(maxTime/100);
animateUpdate();
function updateProgress(percentage) {
    $('#pbar_innerdiv').css("width", percentage + "%");
    $('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
    var now = new Date();
    var timeDiff = now.getTime() - start.getTime();
    var perc = Math.round((timeDiff/maxTime)*100);
    if (perc <= 100) {
        updateProgress(perc);
        setTimeout(animateUpdate, timeoutVal);
    }
}

只需做一些好的老式数学。这似乎是不对的,因为你给出的宽度百分比是"刻度"的值,最终会是835000!意味着您最终拥有"835000%"的宽度!!!

示例

var timer = 0,
    perc = 0,
    timeTotal = 835000,
    timeCount = 50;
function updateProgress(percentage) {
    var x = (percentage/timeTotal)*100,
        y = x.toFixed(3);
    $('#pbar_innerdiv').css("width", x + "%");
    $('#pbar_innertext').text(y + "%");
}
function animateUpdate() {
    if(perc < timeTotal) {
        perc++;
        updateProgress(perc);
        timer = setTimeout(animateUpdate, timeCount);
    }
}
$(document).ready(function() {
    $('#pbar_outerdiv').click(function() {
        clearTimeout(timer);
        perc = 0;
        animateUpdate();
    });
}); 

jsFiddle演示

描述

这只是每10ms增加一次进度。。。既然你知道它需要的时间,就用这个时间除以100,然后在var timer = setInterval(updateProgressbar, 10); 中使它成为你的时间间隔

HTML

<div id="progressbar"></div>

JS

var progress = 0;
var timer = setInterval(updateProgressbar, 10);
function updateProgressbar(){
    $("#progressbar").progressbar({
        value: ++progress
    });
    if(progress == 100)
        clearInterval(timer);
}
$(function () {
    $("#progressbar").progressbar({
        value: progress
    });
});

JS Fiddle只为你

JS

var progress = 0;
var timer = setInterval(updateProgressbar, 8350);
function updateProgressbar(){
    $("#progressbar").progressbar({
        value: ++progress
    });
    if(progress == 100)
        clearInterval(timer);
}
$(function () {
    $("#progressbar").progressbar({
        value: progress
    });
});

您可能想要这样的东西:

var currentTime = new Date().getTime();
perc = (currentTime - StarTime)/duration;

如果也这样设置StartTime,您可以计算每次更新的百分比。