1
\$\begingroup\$

multiple AJAX requests and multiple SetTimeout animations

I wrote a piece of code that included multiple AJAX requests and multiple SetTimeout animations.

I want the code to perform better, especially the SetTimeout sections.

which part of the code should be improved?

thanks

window.timer = [];
window.timerNum = 1;

function amLoading(timer) {
    var node = document.createElement("mark"),
        str = "Loading...",
        len = str.length,
        i = 0,
        html = "";

    node.classList.add("am-load");

    function typing() {
        console.log("timer > " + timer);

        if (i < len) {
            html += str[i];
            i++;
        } else {
            html = "";
            i = 0;
        }

        node.innerHTML = html;

        timer = setTimeout(function () {
            typing();
        }, 160);
    }

    typing();

    return node;
}

function requestData(option) {
    var list = option["list"],
        xhrType = option["type"],
        xhrUrl = option["src"],
        count = option["count"],
        num = window.timerNum++,
        xhr = new XMLHttpRequest(),
        item = document.createElement("li");

    window.timer.push(num);
    // console.log(num);
    // console.log(window.timer[num-1]);
    var node = amLoading(window.timer[num - 1]);

    xhr.open("GET", xhrUrl, true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            if (node) {
                node.parentNode.removeChild(node);
                clearTimeout(window.timer[num - 1]);
            }

            switch (xhrType) {
                case "json":
                    var par = document.createElement("p");
                    par.innerHTML = xhr.responseText;
                    item.appendChild(par);
                    break;
                case "image":
                    var img = document.createElement("img");
                    img.src = xhrUrl;
                    item.appendChild(img);
                    break;
                default:
                    break;
            }

            requestData.num++;
            // console.log(requestData.num);

            if (requestData.num === count) {
                list.classList.add("active");
            } else {
                list.classList.remove("active");
            }
        } else {
            item.appendChild(node);
        }

        list.appendChild(item);
    };

    xhr.send(null);
}

function renderData(option) {
    var wrapper = document.querySelector(option["selector"]),
        data = option["data"],
        requestCount = data.length;

    wrapper.innerHTML = "";

    if (data.length > 0) {
        data.forEach(function (value, index) {
            requestData.num = 0;

            requestData({
                "type": value["type"],
                "src": value["src"],
                "list": wrapper,
                "count": requestCount,
            });
        });
    }
}

var data = [{
        "type": "json",
        "src": "/data.json",
    },
    {
        "type": "image",
        // "src": "/github-logo.png-error",
        "src": "/github-logo.png",
    },
    {
        "type": "image",
        "src": "/node-logo.png",
    },
    {
        "type": "image",
        "src": "/python-logo.png",
    },
    {
        "type": "image",
        "src": "/vim-logo.png-error",
        // "src": "/vim-logo.png",
    },
    {
        "type": "image",
        "src": "/vscode-logo.png",
    },
];

renderData({
    "selector": ".list",
    "data": data,
});
* {
    margin: 0;
    padding: 0;
    list-style: none;
    box-sizing: border-box;
}

body {
    padding: 1rem;
    word-break: break-all;
    word-wrap: break-word;
    color: #666;
}

img {
    display: block;
    max-width: 100%;
}

ol {
    letter-spacing: -8px;
}

ol>li {
    display: inline-block;
    width: 200px;
    height: 200px;
    padding: 1rem;
    letter-spacing: 1px;
    vertical-align: middle;
    border: 1px solid #eee;
    position: relative;
}

ol>li>.am-load {
    padding: 10px;
    height: 36px;
    line-height: 1;
    text-align: center;
    color: #f80;
    position: absolute;
    left: 5%;
    right: 5%;
    top: 50%;
    -ms-transform: translate(0, -50%);
    transform: translate(0, -50%);
}

ol.active>li {
    border-color: #fc8;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Demo-AJAX</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <ol class="list"></ol>
</body>
</html>

\$\endgroup\$
  • \$\begingroup\$ Can you give more context on what this code actually does (instead of just saying it uses multiple timers and XHR calls)? \$\endgroup\$ – Joseph May 2 at 20:41
  • \$\begingroup\$ Your code has bugs that you are aware of as you have console.log("timer > " + timer); trying to track down why the timeouts are not cleared. (amLoading(timer){ timer is a copy not a reference) It is also difficult to workout your intent (Why request the images then ignore the data when it has loaded? Why not create an Image and set its src without the redundant fetch?) To get a good review you will need to fix your code and clarify your intent. \$\endgroup\$ – Blindman67 May 3 at 3:28
  • \$\begingroup\$ @Joseph This code can be executed normally, no bugs. I want to write a JS component. \$\endgroup\$ – Phoenix May 4 at 7:50
  • \$\begingroup\$ @Blindman67 This code can be executed normally. I want to write a JS component. \$\endgroup\$ – Phoenix May 4 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.