简体   繁体   中英

javascript: How to repeatedly call the function itself?

I want to repeatedly count time and update the current time every one minute. My code doesn't work. Firebug console says the final line function getStatus() is not defined. How to call this function repeatedly?

jQuery(document).ready(function($){

    $(function() {   
     getStatus();
    });

    function getStatus() {
      var post_id = $('#post_id').val();
      var nonce = $('#_wpnonce').val();
      jQuery.ajax({
        url : ajaxurl,
        data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
        success: function(response) {
          if(response == "false") {
            alert("failed")
          }
          else {
            $("#message").html(response)
          }
        }
        });
      setTimeout("getStatus()",60000);
    }
    },(jQuery));

your issue is getStatus is wrapped in another callback. either do window.getStatus = function(){} , or turn your code to this:

jQuery(document).ready(function($){
    var getStatus = function() {
      var post_id = $('#post_id').val();
      var nonce = $('#_wpnonce').val();
      jQuery.ajax({
        url : ajaxurl,
        data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
        success: function(response) {
          if(response == "false") {
            alert("failed")
          }
          else {
            $("#message").html(response)
          }
        }
        });
      setTimeout(getStatus,60000);
    };

    $(function() {   
     getStatus();
    });

},(jQuery));

Passing a string to setTimeout will make it eval the string, which you should avoid, and generally not required by your code

You could use setInterval(getStatus, 60000) instead perhaps, but otherwise you should use setTimeout(getStatus, 60000) . Do not use a string as the function callback but rather the named function.

Use setInterval(function, milliseconds)

jQuery(document).ready(function ($) {
    var getStatus = function() {
        var post_id = $('#post_id').val();
        var nonce = $('#_wpnonce').val();
        jQuery.ajax({
            url: ajaxurl,
            data: {
                action: "update_edit_lock",
                post_id: post_id,
                nonce: nonce
            },
            success: function (response) {
                if (response == "false") {
                    alert("failed")
                } else {
                    $("#message").html(response)
                }
            }
        });
    }
    setInterval(getStatus, 1000);
}, (jQuery));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM