简体   繁体   English

递归调用setTimeout函数并传递一个匿名函数

[英]Calling the setTimeout Function recursively and passing an anonymous function

I am confused on the difference between this syntax: 我对此语法之间的区别感到困惑:

var timerId;
 function clockStart(){
    // debugger;
    if(timerId){
      return;
    }
    update();
    // THIS LINE BELOW *********************************************
    var timerId = setTimeout(function(){clockStart()}, 1000);
  }
    function clockStop(){
      timerId = null;
    }
    function update(){
      var date = new Date();
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var seconds = date.getSeconds();
      if(hours < 10) {
        hours = '0'+hours;
      }
      document.getElementById('hour').innerHTML = hours;
      if(minutes < 10){
        minutes = 0+minutes;
      }
      document.getElementById('min').innerHTML = minutes;
      if(seconds < 10){
          seconds = '0' + seconds;
      }
      document.getElementById('sec').innerHTML = seconds;
    }

I provided both functions being called but the main part of this function I do not understand is why I need to pass an anonymous function to call my clockStart() function. 我提供了被调用的两个函数,但是我不了解的该函数的主要部分是为什么我需要传递一个匿名函数来调用我的clockStart()函数。

My function works when I use this syntax: 使用以下语法时,我的函数可以正常工作:

    var timerId = setTimeout(function(){clockStart()}, 1000);

But it doesn't work when I use: 但是当我使用时它不起作用:

    var timerId = setTimeout(clockStart(), 1000);

I have been working a while on these two functions and I honestly stumbled upon this by accident. 我已经在这两个功能上工作了一段时间,老实说,我偶然发现了这两个功能。 I really don't see what the anonymous function is doing besides invoking my clockStart function. 除了调用ClockStart函数外,我真的看不到匿名函数在做什么。 But in my opinion, my clockStart() function should be invoked every second(1000ms) since it is calling itself, so why does it need an anonymous function to invoke it? 但是我认为,由于我的clockStart()函数正在调用自身,因此应该每秒(1000ms)被调用一次,那么为什么它需要一个匿名函数来调用它呢? Shouldn't it be invoking itself? 它不应该自己调用吗?

If you would like to see this digital 'clock's' full code please checkout my codepen link . 如果您想查看此数字“时钟”的完整代码,请查看我的代码笔链接

This line: 这行:

var timerId = setTimeout(clockStart(), 1000);

is calling clockStart() immediately and passing the return result from that function to setTimeout() . 正在立即调用clockStart()并将该函数的返回结果传递给setTimeout() Since the function doesn't return anything, you're effectively doing this: 由于该函数不返回任何内容,因此您可以有效地执行以下操作:

clockStart();
var timerId = setTimeout(undefined, 1000);

which obviously doesn't do what you want. 这显然不能满足您的要求。


You can use this instead: 您可以改用以下方法:

var timerId = setTimeout(clockStart, 1000);

In this case, you want to pass a function reference to setTimeout() which means you do not include the parens. 在这种情况下,您希望将函数引用传递给setTimeout() ,这意味着您不包括括号。 When you include the parens, that means to execute it NOW. 当您包含括号时,表示立即执行。 When you just pass the name of the function, that is just a reference to the function (think of it like a handle) by which setTimeout() can call it later. 当您仅传递函数名称时,它只是对该函数的引用(将其setTimeout()一个句柄), setTimeout()可以在以后对该函数进行调用。 That's what you want. 那正是你想要的。

When you do this: 执行此操作时:

var timerId = setTimeout(function(){clockStart()}, 1000)

you're just defining an anonymous function and passing a reference to that anonymous function to to setTimeout() which works fine, but is not necessary in this case since you can just pass the clockStart name as in my third code example above. 您只是在定义一个匿名函数,并将对该匿名函数的引用传递给setTimeout() ,效果很好,但是在这种情况下不是必需的,因为您可以像上面第三个代码示例中那样传递clockStart名称。


Since you asked about how a function can call something later, I'll show you a simple example. 由于您询问了函数以后如何调用某些内容,因此我将向您展示一个简单的示例。 Here's a function that takes a starting value, an ending value, an increment and a callback function. 这是一个需要一个开始值,一个结束值,一个增量和一个回调函数的函数。 This will call the callback and pass it the value that it's incrementing until the value exceeds the end value. 这将调用回调并将其递增的值传递给它,直到该值超过最终值为止。

// define an increment function that will call a callback
// multiple times based on the start, end and increment arguments
function eachIncrement(start, end, increment, callback) {
    // the function argument named callback contains
    // a function reference
    var val = start;
    while (val <= end) {
        // execute the function reference and 
        // pass it the current val
        callback(val);
        val += increment;
    }
}

// define a function that we want to be called later
function processValues(num) {
    // this will get called multiple times with 
    // values 1, 4, 7, 10
}

// set up the increment parameters and pass a function reference
eachIncrement(1, 10, 3, processValues);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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