Выполнение js функции в течение 10 секунд
Подскажите способ, чтобы функция выполнялась не одномоментно, а в течение 10 секунд.
Есть функция js
function move() {
var barSize = $this.children('button').outerWidth();
var progressBar = $this.children('.fill');
var width = 0;
var id = setInterval(frame, 10);
function frame() {
if(width >=100){
clearInterval(id);
} else {
width++;
progressBar.css( "width", width+'%');
}
}
}
Мне нужно, чтобы она выполнялась в течение 10 секунд, а не сразу или по разу каждую секунду, поэтому (setTimeout) не подходит.
Ответы (2 шт):
Автор решения: Igor
→ Ссылка
var $this = $();
function move() {
var barSize = $this.children('button').outerWidth();
var progressBar = $this.children('.fill');
var width = 0;
var id = setInterval(frame, 100);
function frame() {
console.clear();
console.log('width =', width);
if (width >= 100) {
clearInterval(id);
} else {
width++;
progressBar.css("width", width + '%');
}
}
}
move();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Автор решения: OPTIMUS PRIME
→ Ссылка
var start = performance.now();
var animaTime = 10; // Время анимации в секундах
var FPS = 60; // "кадры" (вызовы функции) в секунду
var width = 0;
var limit = id('progress').clientWidth;
var bar = id('bar');
var updateRate = 1000/FPS;
var updateStep = (limit/FPS) / animaTime;
var interval = setInterval(animaProgress, updateRate);
function animaProgress() {
if (width >= limit) {
bar.style.width = limit;
clearInterval(interval);
console.log( "Прошло (ms):", performance.now() - start );
return;
}
width += updateStep;
bar.style.width = width + "px";
}
function id(str) { return document.getElementById(str); }
#progress {
position: relative;
width: 300px;
height: 20px;
background-color: #ddd;
}
#bar {
position: asolute;
left: 0;
top: 0;
width: 0;
height: 20px;
background-color: orange;
}
<div id="progress">
<div id="bar"></div>
</div>
Выходит небольшое отставание из-за деления 1000/60... Можно сделать 100 вызовов в секунду, чтобы кругленько встало на место за 10 секунд.