The title

Write a mySetInterVal(fn, a, b) at intervals a, a+b, a+2b, and then write a myClear to stop the mySetInterVal above

Analysis of the

  1. A + 0*b, a + 1*b, a + 2*b,…. A plus n times b, so I need a count variable here first
  2. Different timing intervals should be understood as multiple separate timers, so setTimeout() is used.
  3. To stop the timer, you need to save the timer handler (the ID returned by the timer)
  4. With closures, avoid this and expose only what is needed

implementation

function mySetInterVal(fn, a, b) {
    
    let n = 0          / / count
    let hTime = null   // Timing ID, used when stopping
	
    / / 1. Open it
    function start() {
        hTime = setTimeout(() = > {
            fn()
            n++     // When the timer expires, execute these 3 lines of code
            start() // Execute the next timer
	}, a + n*b)
    }
	
    / / 2. Stop
    function myClear() {
        clearTimeout(hTime)
    }
	
    // return only the two methods used as objects.
    return {start, myClear}
}
Copy the code

Tests and Results

var xxx = mySetInterVal(() = > {
        // When the current time
        console.log((new Date).toLocaleTimeString())
        
    }, 1000.2000)
/* Each < interval > is 1 + 0 = 1 SEC 1 + 2 = 3 SEC 1 + 4 = 5 SEC 1 + 6 = 7 SEC 1 + 8 = 9 SEC 1 + 10 = 11 SEC 1 + 12 = 13 SEC */
Copy the code

Also in the front of learning, interested partners can contact. Wechat: H2O_9527 QQ group: 929330787