Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Need help with simple code

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #150076
    Kuzyo
    Participant

    Hi guys;
    Can’t figure out how to make this code work without Global variable i .

    var i = 0;
    function logNum() {
        i++;
        console.log( i );
    }
    
    var timerId = setTimeout(function loop() {
      logNum();
      timerId = setTimeout( loop, 100 );
      if ( i === 20 ) clearTimeout( timerId );
    }, 100);
    

    Can somebody give advice? Thanks

    #150081
    whatsoever
    Participant

    Try this out :)
    It is the same code, you just have to wrap an IIAF around it.

    (function () {
        var i = 0;
        function logNum () {
            i++;
            console.log(i)
        };
    
        var timerId = setTimeout(function loop() {
              logNum();
              timerId = setTimeout( loop, 100 );
              if ( i === 20 ) clearTimeout( timerId );
            }, 100);
    }())
    
    #150094
    Kuzyo
    Participant

    Thanks, this solution I knew but if imagine that all my code already wrapped in immediately-invoked function.

    #150097
    whatsoever
    Participant

    In that case you might as well put your original code in the IIF, it would work.
    There are a lot of ways to handle this, if your IIF returns a object, you could define ‘i’ and numLog inside the function and after that return them, like so:

    var css_tricks = (function () {
        var i = 0;
        //some code
    
        function numLog() {
            i++;
            console.log(i);
            return i;
        }
    
        return {
            numLog: numLog
        }
    }())
    
    var timerId = setTimeout(function loop(){
        var i = css_tricks.numLog();
        timerId = setTimeout(loop, 100)
        if(i === 20) {
            clearTimeout(timerId)
        };
    }, 100) 
    

    It pretty much depends on the effect you are trying to achieve.

    #150155
    Kuzyo
    Participant

    Thanks, it’s nice solution. I’m in process of understanding clouser and other JS tricks and sometimes need help.

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.