HTML
<!DOCTYPE html>
<html>
<head>
<title>Count</title>
</head>
<body>
<div id="value">1000</div>
</body>
</html>
JAVASCRIPT 片段
这是一个简单的 js 函数,将值从给定的起始编号递减到结束编号(对象原型)..
function getCounter(startCount,endcount,time,html){
objects = {
//you can alternateif you want yo add till you reach the endcount
startCount:startCount,
endCount:endcount,
timer:time
}
this.function = function(){
let startTm = objects.startCount,
timer = objects.timer,
endCount = objects.endCount;
//if you want it to add a number just replace the -1 with +1
/*and dont forget to change the values in the object prototype given a variable of counter*/
let increament = startTm < endCount ? 1:-1;
timmer = setInterval(function(){
startTm += increament;
html.innerHTML = startTm ;
if(startTm == endCount){
clearInterval(timmer);
}
},timer);
}
}
// input your startCount,endCount the timer.....
let doc = document.getElementById('value');
let counter = new getCounter(1000,1,10,doc);
//calling the function in the object
counter.function();
查看此演示https://jsfiddle.net/NevilPaul2/LLk0bzvm/