Set a delay in a repeating jQuery / Ajax function

后端 未结 3 1980
醉梦人生
醉梦人生 2020-12-06 02:08

I am trying to add a delay to a repeatable query.

I found out that .delay is not the one to use here. Instead, I should go with setInterval or setTimeout. I tried bo

3条回答
  •  青春惊慌失措
    2020-12-06 02:41

    Note: Chris Kempen's answer (above) is better. Please use that one. He uses this technique inside the AJAX routine. See this answer for why using setTimeout is preferable over setInterval.


    //Global var
    is_expired = 0;
    
    $(function (){
    
        var timer = setInterval(doAjax, 800);
    
        //At some point in future, you may wish to stop this repeating command, thus:
        if (is_expired > 0) {
            clearInterval(timer);
        }
    
    }); //END document.ready
    
    function doAjax() {
        $.ajax({                                      
            cache: false,
            url: 'ajax2.php',        
            data: "workerID=",
            dataType: 'json',    
            success: function(data) {
                var id = data[0];              //get id
                var vname = data[1];           //get name
                //--------------------------------------------------------------------
                // 3) Update html content
                //--------------------------------------------------------------------
                $('#output').html("id: "+id+" name: "+vname);
            }
        }); //END ajax code block
    } //END fn doAjax()
    

提交回复
热议问题