Home  >  Article  >  Backend Development  >  javascript - A number is incremented by 1 every second and printed out until it reaches 50. How to implement this using js?

javascript - A number is incremented by 1 every second and printed out until it reaches 50. How to implement this using js?

WBOY
WBOYOriginal
2016-10-17 09:30:093155browse

As in the question, how to solve the problem using closure and setTimeout function?
PHP implementation is also welcome

Reply content:

As in the question, how to solve the problem using closure and setTimeout function?
PHP implementation is also welcome

<code>var count = (function() {
    var timer;
    var i = 0;
    function change(tar) {
        i++;
        console.log(i);
        if (i === tar) {
            clearTimeout(timer);
            return false;
        }
        timer = setTimeout(function() {
            change(tar)
        }, 1000)

    }
    return change;
})()

count(50)</code>

<code>(function(){
    var i=0;
    var end=setInterval(function(){
        if(i>=50){
            clearInterval(end);
        }
        console.log(i);
        i++;
    },1000);
})()</code>

If you use setTimeout, there is no need to clear.

<code>void function loop(i) {
    if (i <= 50) {
        console.log(i);
        setTimeout(loop.bind(this, ++i), 1000);
    }
}(1);</code>

It seems that closure is not used, so let’s do this:

<code>void function loop(i) {
    if (i <= 50) {
        console.log(i);
        setTimeout(function() {loop(++i);}, 1000);
    }
}(1);</code>

OK, now we have closure.

function Count(){

<code>    var counter=0;
    function addCount(){
        counter++;
        console.log(counter);
        if(counter==50){
            return false;
        }
        setTimeout(addCount,1000);
    }
    return addCount;
}
var myCount=new Count();
myCount();</code>

<code>var task = function (){
    var val = 0;
    var target = 50;
    
    (function add(){
        val++;
        if(val === target)
            return;
            
        setTimeout(add, 1000);    
    })();
}</code>

You can’t stop this

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn