最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Settimeout in next jsreact - Stack Overflow

programmeradmin3浏览0评论
let i = 0

function pollDOM() {     
  console.log(i)

  i++

  setTimeout(pollDOM, 3000) // try again in 300 milliseconds
}

pollDOM()

The above function use to run every 3 second, output is like:

1 

// wait 3 seconds

2 

// wait 3 seconds

3 

// wait 3 seconds

4 

// wait 3 seconds, and so on...

But in Next.js, it produces a result as:

1
2 

// wait for 3 seconds

3
4

// wait for 3 seconds

5
6

// wait for 3 seconds, and so on...

Why it is produced this way, two numbers together?

How can I achieve that that I am achieving in normal JavaScript?

let i = 0

function pollDOM() {     
  console.log(i)

  i++

  setTimeout(pollDOM, 3000) // try again in 300 milliseconds
}

pollDOM()

The above function use to run every 3 second, output is like:

1 

// wait 3 seconds

2 

// wait 3 seconds

3 

// wait 3 seconds

4 

// wait 3 seconds, and so on...

But in Next.js, it produces a result as:

1
2 

// wait for 3 seconds

3
4

// wait for 3 seconds

5
6

// wait for 3 seconds, and so on...

Why it is produced this way, two numbers together?

How can I achieve that that I am achieving in normal JavaScript?

Share Improve this question edited May 28, 2022 at 10:51 Roman Mahotskyi 6,6958 gold badges50 silver badges93 bronze badges asked May 28, 2022 at 10:45 Ravi ShankarRavi Shankar 1451 gold badge4 silver badges14 bronze badges 1
  • 1 what do you mean by in Next.js ? Can you show us your Component ? Without more information about your code, it's really difficult to help you ! – Olivier Boissé Commented May 28, 2022 at 10:53
Add a ment  | 

1 Answer 1

Reset to default 7

Bacause when your ponent is rendered for a second time you're adding the setTimeout again. You have to clear your timeout and use useEffect to set it only once, when the ponent is crated. Also, use setInteval instead of setTimeout when you have to repeat something every x seconds. Try:

useEffect(() => {
  let i = 0;

  function pollDOM() {
    console.log(i);
    i++;
  }
  
  const interval = setInterval(pollDOM, 3000);
  
  return () => clearInterval(interval);
}, [])
发布评论

评论列表(0)

  1. 暂无评论