为什么这个Js / jquery代码使用%70的CPU?

时间:2015-06-27 22:45:32

标签: javascript jquery cpu

我使用下面的代码块来更新我的进度条和其他一些内容。但有些事情是错的。当这个页面加载我的CPU工作就像疯了一样。我在N秒后停止,所以在5秒后一切都必须完成。我错了吗?

var start      = new Date();
var maxTime    = 5000;
var maxTimeSec = maxTime / 1000; //convert ms to sec : 20000 / 1000 = 20 sec
var timeoutVal = Math.floor( maxTime / maxTimeSec ); //every 1 second

var counter = 0;
var tt      = setInterval(function(){ animateUpdate() },1000);

//Call function
animateUpdate();

//Check is user logined
function isLogined(){
    userId = $("#userInfo").attr("data-user") ;
    userId = parseInt(userId);
    var logined = false;
    if(userId > 0){
        logined = true;
    }
    return logined;
}

//send some data to somewhere
function sendStat(){
    var lang  = $("#langCode").attr("data-lang");
    var url   = $("#pageUrl").attr("data-pageUrl");
    var title = $("#pageTitle").attr("data-pageTitle");
    var user  = $("#user").attr("data-user");

    $.ajax({
        type: "POST",
        url: "/actions/setStats.php",
        data: {
            "url"       : url,
            "langCode"  : lang,
            "title"     : title,
            "user"      : user
        },
        success: function(res){
            console.log(res);
        }
    });
}

//My timer
function animateUpdate() {
    var now      = new Date();
    var timeDiff = now.getTime() - start.getTime();

    //var sec      = maxTimeSec - Math.round( (timeDiff/maxTime) * maxTimeSec );
    var perc     = Math.round( (timeDiff/maxTime)*100);
    //console.log(perc);

    if(counter > maxTimeSec) {
        clearInterval(tt);
        var bottomDiv = $('#bottomDiv');
        bottomDiv.show();

        if( isLogined() ){
            bottomDiv.text("Congratulations. You're lucky to read this article. We've updated your score.");
        }else{
            bottomDiv.text("Congratulations. You're lucky to read this article. If want to count your score you must login :)");
        }
        sendStat();
    } else {
        $('#timerProgress').css("width", perc + "%");
        $('#timerCountdown').text(perc + "%");
        //setTimeout(animateUpdate, timeoutVal);
        counter++;
    }
} 

1 个答案:

答案 0 :(得分:1)

也许您应该尝试使用jQuery.animate()进行回调?

实施例: http://codepen.io/anon/pen/JdMNem