猿问

无法调用模板文字中的函数

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


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


DIEA
浏览 110回答 3
3回答

慕森卡

当您不从函数返回任何内容时,隐式undefined返回。因此你会得到You have undefined seconds.</p>你必须从你的函数中返回一个值。即使你从你的函数返回一个值,你也会得到你作为参数传递的相同值,因为setInterval本质上是异步的,这意味着在时间间隔开始和结束时你的函数已经返回了该值。function startCountdown(seconds) {&nbsp; let counter = seconds;&nbsp; const interval = setInterval(() => {&nbsp; &nbsp; console.log(counter);&nbsp; &nbsp; counter--;&nbsp; &nbsp; if (counter < 0) {&nbsp; &nbsp; &nbsp; clearInterval(interval);&nbsp; &nbsp; }&nbsp; }, 1000);return counter;}You have 5 seconds.</p>如果你5作为参数传递给你的函数,你会得到。

回首忆惘然

看看这段代码:function startCountdown(seconds) {&nbsp; &nbsp; let counter = seconds;&nbsp; &nbsp; const interval = setInterval(() => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(counter);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; document.querySelector('#countdown').innerHTML = counter;&nbsp; &nbsp; &nbsp; &nbsp; counter--;&nbsp; &nbsp; &nbsp; &nbsp; if (counter < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clearInterval(interval);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, 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.&nbsp;您可以使用 JS 更新此元素。

繁星点点滴滴

您可以提供一个回调,作为回报提供秒数:function startCountdown(sec, cb) {&nbsp; const itv = setInterval(() => {&nbsp; &nbsp; cb(sec); // Call your Callback, pass sec as argument.&nbsp; &nbsp; sec--;&nbsp; &nbsp; if (sec < 0) clearInterval(itv);&nbsp; }, 1000);}// Use your function:startCountdown(5, (sec) => {&nbsp; document.body.innerHTML = `<p>Quick! Click to stop the page from self destructing. You have ${sec} seconds.</p>`;});这样你就可以重用你的startCountdown()代码而不用硬编码到它不相关的东西中。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答