2017-08-23 272 views

回答

2

使用setInterval函數

var n = 0, 
    timerID; 
var myOdometer; 
var div = document.getElementById("odometerDiv"); 
myOdometer = new Odometer(div, { 
    value: n, 
    digits: 6, 
    tenths: true 
}); 
myOdometer.set(0); 

function startcounting() { 


    timerID = setInterval(function() { 
    n = n + 0.01 
    myOdometer.set(n); 
    }, 200); 

} 

//]]> 

startcounting(); 


var started = true; 

$('button').click(function() { 

    if (started) 
    clearTimeout(timerID); 

    else 
    startcounting(); 

    started = !started; 

    var currentvalue = myOdometer.get(); 
    $('#value').text(currentvalue); 
}); 

fiddle

1
var n = 0; 
var timer; 
var myOdometer; 
function startcounting() { 
var div = document.getElementById("odometerDiv"); 
myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true}); 
myOdometer.set(0); 
update(); 
} 

function update() { 
timer = setInterval(function() { 
n = n + 0.01 
myOdometer.set(n);}, 200);} 
startcounting(); 
var state = true; 
$('button').click(function() { 
if (state) 
clearTimeout(timer); 
else 
update(); 
state = !state; 
var currentvalue = myOdometer.get(); 
$('#value').text(currentvalue); 
});