Home > Backend Development > PHP Tutorial > 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
Release: 2016-10-17 09:30:09
Original
3188 people have browsed it

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>
Copy after login

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

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>
Copy after login

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>
Copy after login

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>
Copy after login

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

You can’t stop this

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template