Flexible and general progress bar management component in JavaScript


Talk nonsense firstThis article comes from some achievements in the process of making cars behind closed doors. I will be happy if I take it from myself, change it at will, use it at will, and benefit others.

Main topic

When dealing with drawings, there are many steps, and the total amount of work is unknown, so it is not easy to complete the requirement of progress display on UI.

Here is a simple and useful progress setting and update tool: updater.js

It can dynamically set the remaining workload to adapt to the evaluation of progress in different processes.

//For example, if you only know four big steps at first, you can:

    let updater = updaterCreate(_, 4, cb);

//Complete two steps, using:


//Find the third step, there are 1000 small steps:

    updater.adjustLeft (1000 + 50); // because there is still a big step, it takes 50 steps to reserve its assumption;
    for(let i = 0; i < 1000; i++)

//After the third step is completed, there are 2000 small steps in the fourth step

    updater.adjustLeft (2000); // if there are no more steps, you don't need to leave them;
    for(let i = 0; i < 2000; i++)

The code is as follows:

//We need to monitor the progress of this logic
//CB function parameters are as follows:
//{message, percent}

export default function updaterCreate(name, total, cb) {
    let leftSteps = total;
    let completePercent = 0;

    function _updatePercent(percent) {
            message: `${name} ${percent}/100`,

    function addStep(n) {
        if (completePercent >= 100) return;

        //Replenish the current number of steps
        let step = ('number' === typeof (n)) ? n : 1;
        if (step > leftSteps) step = leftSteps;

        //Update percentage
        let lastPercent = completePercent;
        completePercent += step * (100 - completePercent) / leftSteps;

        //Before and after the percentage is not the same
        if (parseInt(completePercent) !== parseInt(lastPercent))

        leftSteps -= step;

    function adjustLeft(steps) {
        leftSteps = steps;

    return {addStep, adjustLeft};

/* test

import updaterCreate from './util/updater'

let leftStep = 4;

console.log(`updaterCreate(_, ${leftStep}, _);`);

Let {addstep, adjustleft} = updatercreate ({message, percent}) = >{



leftStep = 9999999;

for (let i = 0; i < leftStep; i++) {

console.log(`All steps complete.`);


Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]