【问题标题】:Unable To Invoke Function In A Template Literal无法在模板文字中调用函数
【发布时间】:2021-01-06 02:51:28
【问题描述】:

你好 StackOverflow 英雄,

我有一个业余问题,为什么我不能在模板文字中调用这个函数。代码返回未定义,控制台中没有任何错误。我似乎看不出我做错了什么,我是否缺少退货声明?

function startCountdown(seconds) {
  let counter = seconds;

  const interval = setInterval(() => {
    console.log(counter);
    counter--;

    if (counter < 0) {
      clearInterval(interval);
    }
  }, 1000);
}

document.body.innerHTML = `<p>Quick! Click to stop the page from self destructing. You have ${startCountdown(
  5
)} seconds.</p>`;

谢谢!

【问题讨论】:

  • 您正在插入函数的返回值,但它不返回任何内容。即使你做到了return counter;,这也不会延续到未来;可见值将保持为 5。固定版本:jsfiddle.net/grqok53m

标签: javascript function setinterval template-literals


【解决方案1】:

您可以提供一个回调,作为回报提供秒数:

function startCountdown(sec, cb) {
  const itv = setInterval(() => {
    cb(sec); // Call your Callback, pass sec as argument.
    sec--;
    if (sec < 0) clearInterval(itv);
  }, 1000);
}

// Use your function:
startCountdown(5, (sec) => {
  document.body.innerHTML = `<p>Quick! Click to stop the page from self destructing. You have ${sec} seconds.</p>`;
});

这样你就可以重复使用你的startCountdown(),而不用硬编码到不相关的东西中。

【讨论】:

    【解决方案2】:

    当您不从函数中返回任何内容时,会隐式返回 undefined。因此你会得到You have undefined seconds.&lt;/p&gt;

    你必须从你的函数中返回一个值。

    即使你从你的函数返回一个值,你也会得到与作为参数传递的相同的值,因为setInterval 本质上是异步的,这意味着在时间间隔开始和结束时你的函数已经返回了值.

    function startCountdown(seconds) {
      let counter = seconds;
    
      const interval = setInterval(() => {
        console.log(counter);
        counter--;
    
        if (counter < 0) {
          clearInterval(interval);
        }
      }, 1000);
    
    return counter;
    }
    

    如果您将5 作为参数传递给您的函数,您将获得You have 5 seconds.&lt;/p&gt;

    【讨论】:

      【解决方案3】:

      看看这段代码:

      function startCountdown(seconds) {
          let counter = seconds;
      
          const interval = setInterval(() => {
              console.log(counter); 
              document.querySelector('#countdown').innerHTML = counter;
              counter--;
      
              if (counter < 0) {
                  clearInterval(interval);
              }
          }, 1000);
      }
      
      document.body.innerHTML = `<p>Quick! Click to stop the page from self destructing. You have <span id="countdown">5</span> seconds.</p>`;
      
      startCountdown(5);

      它有一个带有id 的跨度集。然后你可以用 JS 更新这个元素。

      【讨论】:

      • 这仍然以undefined 开头。 &lt;span&gt; 应该由 startCountDown 函数返回。
      • 更新答案。
      猜你喜欢
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 2021-01-14
      • 1970-01-01
      相关资源
      最近更新 更多