0

I'm looking for the most easiest way to fill a progress bar using JS, the progress bar itself should be filled dynamically.

I've received the following code so far from a friend:

        var goal = moment.utc('2023-03-16 21:59:03')
        var start = moment.utc('2023-03-15 21:59:03')
        var now = moment.utc()
        var percComplete = 0;

        var countdownProgress = function () {
            now = moment.utc()

            var diff = goal.diff(now);
            var time = moment.utc(diff).format('HH:mm:ss');
            var percComplete = (now - start) / (goal - start) * 100;

            console.log(goal - now);

            if (percComplete < 100) {
                document.querySelector('.js-countdown-text').innerHTML = `${time}`;
                document.querySelector('.js-countdown-progress').setAttribute('style', `width: ${percComplete}%;`);
            } else {
                document.querySelector('.js-countdown-text').innerHTML = `00:00:00`;
                document.querySelector('.js-countdown-progress').setAttribute('style', `width: 100%;`);
            }

I want to get rid of the start var, because the start time should be "now" all the time. Is there an easy way to modify this code to keep the functionality, but just get rid of this "start in the past" feature?

When I just use:

var percComplete = now / (goal - now) * 100;

it won't work and I don't understand exactly how to the calculation process itself using JS.

gamedev
  • 45
  • 1
  • 6
  • "*I'm not asking how to get the current time using momentJS, this is known to me (by using moment.utc()*" Because your goal is to use the current time instead of `start` and `moment.utc()` gives you the current time, then use `moment.utc()` instead of `start`. What other answer do you expect for this? – VLAZ Mar 16 '23 at 11:15
  • Clarified in first post (2nd edit. – gamedev Mar 16 '23 at 11:20
  • `var start = moment.utc('2023-03-15 21:59:03')` -> `var start = moment.utc()` in your snippet and don't change anything else. Otherwise `now / (goal - now)` makes no sense. `(goal - start)` is the *total time* and `(now - start)` is the *elapsed time*. Dividing elapsed by total gives you the percentage done. `(goal - now)` is nothing meaningful. If you know a task should finish at 10:32 and it's currently 10:30 you don't know how much of the task has been done because there is no reference for the start time. `now / (goal - now)` is essentially `10:30 / (10:32 - 10:30)` thus still meaningless. – VLAZ Mar 16 '23 at 11:46
  • `it won't work`... what's not working? Even after your edits I still don't understand what problem you're having. What's the expected value of percComplete and the value you're getting? – Mike Szyndel Mar 19 '23 at 08:16

0 Answers0