如何在 setInterval/setTimeout 函数中按名称调用函数

How to call a function by name within a setInterval/setTimeout function?

本文关键字:函数 调用 setTimeout setInterval      更新时间:2023-09-26
function loadDate() 
{
    $.ajax({
        type : "POST",
        url : "/ajax/date",
        data : "text",
        success : function(response) 
        {
            $('#dateSection').html(response);
        },
        error : function(e) 
        {
            alert('Ajax Request Failed: ' + e);
        }
    });
}
function loadPoop() 
{
    if(true)
    $.ajax({
        type : "POST",
        url : "/ajax/poop",
        data : "text",
        success : function(response) 
        {
            $('#poopSection').html(response);
        },
        error : function(e) 
        {
            alert('Ajax Request Failed: ' + e);
        }
    });
}

这基本上是我想做的,但我尝试的除了打一个电话之外什么都没有

function ajaxCaller(function_name)
{   
    setInterval(window[function_name], 1000);
    //or
    setInterval(function_name, 1000);
}

网页

<button type="button" onclick="loadDate()">Date Button</button>
<div id="dateSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadDate())">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadPoop())">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>

JavaScript 中的函数是一等对象。这意味着您可以像使用任何其他普通变量一样使用它们。如果 HTML 代码中的括号不省略:

<button type="button" onclick="ajaxCaller(loadDate)">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadPoop)">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>

你告诉 JavaScript 不要调用函数 loadPooploadDate,而是直接将其作为变量传递给函数 ajaxCaller

使用括号 ((,您首先运行loadDate,然后将 loadDate 的结果传递给 ajaxCaller。在这种情况下,loadDateloadPoop 都不返回任何内容,因此 ajaxCaller 也不会收到任何内容,并且不会设置超时。

Samw 的回答是正确的——但我想尝试详细说明一下这个问题。

在你的代码中,你将 loadPoop(( 和 loadDate(( 的返回值作为参数传递给 ajaxCaller((。基本上 - 首先调用 loadPoop((,然后它返回的值(在您的情况下没有任何内容(被传递给 ajaxCaller((。

在 Samw 的答案中,指向函数 loadPoop(( 和 loadDate(( 的指针作为参数传递,允许您稍后使用 function_name(( 调用函数。setInterval也发生了同样的事情,您将一个指针传递给要在setInterval中调用的函数作为参数。

如果您不将参数视为对象或值,而是将其视为地址,那么这更有意义 - 基本上发生的情况是代码的执行"跳转到内存地址(变量名称就是我们人类所说的特定内存地址( - 并且由于函数在内存中的该点开始执行 - 它只是继续。

现在这可能有点过于简单化,但希望它能让您更好地了解为什么这是可以的,以及为什么您的方法不起作用。

欢迎来到指针的世界!

由于您使用的是jQuery,因此我倾向于稍微修改代码以利用它。您可以分离出内联代码,这是一件好事,并且可以通过传入函数参数将 ajax 函数的数量减少到一个。

<button type="button" data-fn="default">Date Button</button>
<div id="dateSection">Ajax Me Bro!</div>
<button type="button" data-fn="date">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" data-fn="poop">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
$(function () {
  function loadAjax(fn) {
    $.ajax({
      type: "POST",
      url: "/ajax/" + fn,
      data: "text",
      success: function (response) {
        $('#' + type + 'Section').html(response);
      },
      error : function (e) {
        alert('Ajax Request Failed: ' + e);
      }
    });
  }
  }
  $('button').click(function () {
    var fn = $(this).data('fn');
    switch (fn) {
      case 'date':
        setTimeout(function () {
          loadAjax('date');
        }, 1000);
        break;
      case 'poop':
        setTimeout(function () {
          loadAjax('poop');
        }, 1000);
        break;
      default:
        loadAjax('date');
        break;
    }
  });
});

声明 :

function ajaxCaller(fn) {   
    setInterval(fn, 1000);
}

用法:

ajaxCaller(loadDate) // instead of : ajaxCaller(loadDate())
ajaxCaller(loadPoop) // instead of : ajaxCaller(loadPoop())

不要自己打电话给fnsetInterval做这项工作。

我认为参数不能是一个函数!! 无论如何,只需使用以下

function ajaxCaller(value)
{
if (value=="loadPoop")

setInterval(function(){loadPoop()},1000);
if (value=="loadPoop")
setInterval(function(){loadDate()},1000);
}

并将参数更改为字符串

<button type="button" onclick="ajaxCaller("loadDate")">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller("loadPoop")">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>

我认为这里的解决方案更具动态性:当我的名字作为字符串时,如何执行JavaScript函数