search

Home  >  Q&A  >  body text

javascript - There are too many timers in js script, how to resolve conflicts?

Business needs, multiple scheduled tasks are written in the js script, as follows:

setTimeout(cron, 120000);//定时上传记录信息
setTimeout(start_init, 350000);

function cron() {
    $.post('cron.php', {state: 'cron'}, function(data) { });
    setTimeout(cron, 120000);
}

function start_init() {
    $.post('start_init.php', {state: 'start_init'}, function(data) { });
    setTimeout(start_init, 350000);
}

/**
* 这段是逻辑处理
**/
var clear_t;
document.onkeydown = function(e){  
    var ev = document.all ? window.event : e;
    if(ev.keyCode==13) {
        clearTimeout(clear_t);

        $.post('ajax.php', send_data, function(data) {
            var jsonRes = JSON.parse(data);
            if(jsonRes.status == 202) {
                /**业务代码块**/

            }else if(jsonRes.status == 200 || jsonRes.status == 2000) {
                /**业务代码块**/

            }else {
                /**业务代码块**/
            }
            clear_t = setTimeout(clear_content, 5000);
        }
    }
}

/**
 * 更改页面部分信息的方法
 */
function clear_content() {
    $("#username").text('******'); 
    $("#useroperations").text('******'); 
    $("#last_balance").text(0);
    $("#consum").text(0); 
    $("#now_balance").text(0);
    local_soc.emit('cum_num', 0);
}

As shown in the above code (The two timers at the top of the code have no special meaning, they are posted to illustrate that there are many timers in this script), jsIn the script A lot of timers are used, so let’s not talk about these timers, which send requests to the server asynchronously, but change some information on the pageclear_contentThe method is here, Sometimes it is easy to break the code, and this code will not be executed from time to time. Is this caused by conflicts between multiple timers? So how to avoid such problems? Or how to improve this program block?

By the way, a special note is to capture the mouse enter event, that is, the bottom code block is executed very frequently, almost 3~5s will be executed once.

迷茫迷茫2757 days ago1049

reply all(1)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-06 09:55:37

    https://zhuanlan.zhihu.com/p/...

    reply
    0
  • Cancelreply