首页 > 解决方案 > Returning from setInterval in JavaScript/React.js

问题描述

I'm trying to return a value from my setInterval function. My code looks like that:

export const timeCounter = () => {
  const date = "2018-08-12T18:45:00.000Z"; //this is just mocked data
  const matchDate = new Date(date);

  let dateToShow;

  const showTime = () => {
    const currentDate = new Date();
    const distance = matchDate - currentDate;

    return dateToShow = distance < 0 ? "FINISHED" : null;
  };


  const timer = setInterval(showTime, 1000);
  console.log(timer) // here I'd like to see refreshing value (FINISHER or nothing)
};

What I'm trying to do is to run my interval every second with showTime function. What I need to return is just "FINISHED" or nothing. But console.log(timer) won't give refreshed status. Thanks for helping.

标签: javascript

解决方案


setInterval不会返回您期望的字符串 'FINISHED' 或 null,但它会返回唯一标识间隔的间隔 ID,因此您可以稍后通过调用将其删除clearInterval()。此方法在 Window 和 Worker 接口上提供。


推荐阅读