jquery 调用函数时定义超时

jquery define timeout when calling function

我坚持让超时工作。我已经有了一个工作代码,但在我看来这是错误的方法。

工作代码但可能不是最好的:

/* Autosave */
// On load we hide all autosave messages.
$('.jform_params_autosave-cg').hide();
// Below is the function that handles the autosave.
$.fn.autoSave = function(){
  // We remove the autosave message from it's place defined by the xml and add it to the system message container.
  var autosavemessage = $('.jform_params_autosave-cg');
  autosavemessage.detach();
  autosavemessage.appendTo('#system-message-container');
  // Now we show the message.
  $('.jform_params_autosave-cg').show();
  // Here we save the extension.
  Joomla.submitbutton('module.apply');
}
// On change of the below elements we run the autosave.
//------------------------------------------//
// DUPLICATE AUTOSAVE FUNCTION BELOW
//------------------------------------------//
// Autosave: Theme Selection
$("#jform_params_theme_selection").change(function() {
  $.fn.autoSave();
});
// Autosave: Add Content
$("a.group-add.btn.btn-mini.button.btn-success").click(function() {
  setTimeout(
    function()
    {
      $.fn.autoSave();
    }, 5000);
});

函数:

$.fn.autoSave = function(){
  // We remove the autosave message from it's place defined by the xml and add it to the system message container.
  var autosavemessage = $('.jform_params_autosave-cg');
  autosavemessage.detach();
  autosavemessage.appendTo('#system-message-container');
  // Now we show the message.
  $('.jform_params_autosave-cg').show();
  // Here we save the extension.
  Joomla.submitbutton('module.apply');
}

函数调用

$("#jform_params_theme_selection").change(function() {
  $.fn.autoSave();
});

超时函数调用

$("a.group-add.btn.btn-mini.button.btn-success").click(function() {
  setTimeout(
    function()
    {
      $.fn.autoSave();
    }, 5000);
});

我想达到什么目标

  1. 在函数内设置超时。
  2. 定义调用函数的超时时间。

关于定义,我的意思是称它为 $.fn.autoSave(5000);$.fn.autoSave().timeout(500);

我一直在努力获得一个有效的代码,但到目前为止还没有成功。每当我获得更多成功或要添加的详细信息时,将继续更新此 post。

感谢大家的帮助。

对现有 SO 问题的任何 link 也将不胜感激,因为我可能在谷歌上搜索了错误的关键词。

这是您函数的修改版本。现在它有可选的超时参数。你可以像

一样使用它

$('selector').autoSave(5000)$('selector').autoSave()

$.fn.autoSave = function(timeout) {
  function doIt() {
    // We remove the autosave message from it's place defined by the xml and add it to the system message container.
    var autosavemessage = $('.jform_params_autosave-cg');
    autosavemessage.detach();
    autosavemessage.appendTo('#system-message-container');
    // Now we show the message.
    $('.jform_params_autosave-cg').show();
    // Here we save the extension.
    Joomla.submitbutton('module.apply');
    return this;
  }
  timeout = Number(timeout) || 0;
  var f = doIt.bind(this);
  if(timeout < 0) return f();
  setTimeout(f, timeout);
  return this;
}