How do I correctly use setInterval and clearInterval to switch between two different functions?

前端 未结 6 437
-上瘾入骨i
-上瘾入骨i 2020-12-01 12:53

For practice I am trying to display a number that increments from 0 - 9, then decrements from 9 - 0, and infinitely repeats.

The code that I have so far seems to

6条回答
  •  春和景丽
    2020-12-01 13:24

        /** Tools */
    const log = require('ololog').configure({
      locate: false
    })
    
    let count = 0
    let interval__UP
    let interval__DOWN
    
    function countUp () {
      count++
      log.green('countUp(): ', count)
    
      if (count == 5) {
        clearInterval(interval__UP)
        interval__DOWN = setInterval(function () {
          countDown()
        }, 1000)
      }
    
    }
    
    function countDown () {
    
      count--
      log.red('countDown(): ', count)
    
      if (count == 0) {
        clearInterval(interval__DOWN)
        interval__UP = setInterval(function () {
          countUp()
        }, 3000)
      }
    }
    
    function start () {
      countUp()
      log.cyan('start()')
      interval__UP = setInterval(function () {
        countUp()
      }, 2000)
    }
    
    start()
    

    Console Log shows it's working

提交回复
热议问题