Slow execution of JS script

旧巷老猫 提交于 2019-12-13 21:33:56

问题


I have a simple script to toggle post image/text on onmouseover. The code works fine if there are no more than 2 posts, but it becomes VERY slow when the number of posts increases.

function showPost(ele, eve) {
    var id = ele.id.replace("post-", "");
    if (typeof window['timerHide-' + id] !== "undefined") {
        clearInterval(window['timerHide-' + id]);
    }
    var target = (eve.relatedTarget) ? eve.relatedTarget : eve.toElement;
    var parent = $("post-" + id);
    if (typeof target === "undefined" || target === parent || target.parentNode === parent || target.parentNode.parentNode === parent) {
        return;
    }
    var img = $("post-img-" + id);
    var txt = $("post-txt-" + id);
    if (img.style.opacity === "") {
        img.style.opacity = 1;
    }
    var opacity = img.style.opacity;
    window['timerShow-' + id] = setInterval(function () {
        if (opacity <= 0.1) {
            clearInterval(window['timerShow-' + id]);

            img.style.display = 'none';
            txt.style.display = 'block';
            txt.style.opacity = 1;
        }
        img.style.opacity = opacity;
        img.style.filter = 'alpha(opacity=' + opacity * 100 + ")";
        opacity -= opacity * 0.1;
    }, 1);
};

The other function is almost identical to this one except for that it hides the toggled text.


回答1:


You seem to be saving the interval ID to a DOM element, try using a variable

var timerID = setInterval(function ()
if (opacity <= 0.1)
{
    clearInterval(timerID);


来源:https://stackoverflow.com/questions/21589210/slow-execution-of-js-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!