简体   繁体   中英

How does the flow of this code work when this function using `setInterval` and `setTimeout` is called?

This function was supposed to highlight and unhighlight a button for some time interval and then finally pick a button:

function randomSelect() {
  const times = 30
  const interval = setInterval(() => {
    const randomTag = pickRandomTag()
    
    highlightTag(randomTag)
    setTimeout(() => {
      unHighlightTag(randomTag)
    }, 100)
  }, 100);

  setTimeout(() => {
    clearInterval(interval)
    setTimeout(() => {
      const randomTag = pickRandomTag()

      highlightTag(randomTag)
    }, 100)
  }, times * 100)
}

I'm not understanding the flow of this code because changing the time ( times * 100 ) of the second setTimeout changes the interval of highlight and unhighlight function of the first timeout.

In this code one randomTag is being highlighted every 100ms with the help of first setinterval and then after 100ms it gets unhighlighted with settimeout, so at a time only one tag is highlighted.

After this with the help of second setTimeout the previous setinterval is getting cleared after (times*100)ms ie3000ms (meanwhile 30 times one random tag is highlghted and unhighlighted) and again after 100ms of the setimeout execution one tag gets highlighted beacause of inner setTimeout of second setTimeout and remains highlighted.

This function acts like a random lottery tag picker where you can see the different tags getting highlighted and unhighlighted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM