Home > Blockchain >  My interval is not continuing after gets called second time
My interval is not continuing after gets called second time

Time:06-07

enter image description here

what i tried

let intervalTimer = null;
function startTimer(callback, interval) {
    // Write the code that goes here
    intervalTimer = setInterval(() => {
        let obj = {number:0};
        if(callback(obj)) {

        } else {

        }
    },interval);
}
  
function callback(obj) {
obj.number  
console.log(obj.number);
return obj.number < 5;
}

this is my code so far - but i only manage to get 1. After that the eecution is not continuing. How can i solve this ?

CodePudding user response:

Place the let obj = {number:0}; outside the function closure, just like you did with the let intervalTimer. Because your adding zero to the callback, its gets incremented by 1,then it gets set back to 0.

CodePudding user response:

In the original, obj is being recreated each time the interval fires, hence it never advances.

This also returns the interval ID to the caller, allowing for multiple timers as per the requirement.

function startTimer(callback, interval) {

    let obj = {number:0};

    const intervalTimer = setInterval(() => {
        if(!callback(obj)) {
            clearInterval(intervalTimer)
        }
    },interval)

    return intervalTimer
}

function callback(obj) {
    obj.number  
    console.log(obj.number)
    return obj.number < 5
}

const timer1 = startTimer(callback, 500)
const timer2 = startTimer(callback, 750)

CodePudding user response:

The following demonstrates the concurrent running of two timers. Each timer callback will log a value based on its counter variable. The first timer operates on an interval of 500ms, and the second, 1000ms.

Note the use of the logical OR operator (||):

  • If the left-hand side of the operator evaluates to a truthy value (ie. we should continue), then the right-hand side (timer cancellation) is not evaluated.

  • If the left-hand side of the operator evaluates to a falsy value, then the right-hand side (the cancellation) is evaluated, and the timer stops.

const startTimer = (callback, interval = 1000) => {
    let counter = 1
    const tick = () => 
        (callback(counter  ) || clearInterval(intervalId))
    const intervalId = setInterval(tick, interval)    
}

const countToTen = (counter) => {    
    console.log(counter)
    return counter < 10
}

const abcs = (counter) => {    
    // 65 is the start of the Latin Alphabet
    console.log(String.fromCharCode(64   counter)) 
    return counter < 10
}

startTimer(countToTen, 500)
startTimer(abcs)

  • Related