首页 > 解决方案 > 无法在模板文字中调用函数

问题描述

你好 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>`;

谢谢!

标签: javascriptfunctionsetintervaltemplate-literals

解决方案


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

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

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

function startCountdown(seconds) {
  let counter = seconds;

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

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

return counter;
}

You have 5 seconds.</p>如果你5作为参数传递给你的函数,你会得到。


推荐阅读