每2秒打印一次从1到10的数字 [英] print number from 1 to 10 after every 2 seconds

查看:90
本文介绍了每2秒打印一次从1到10的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每隔n秒打印一次数字,并且基于一些条件,我正在更改计时器以及停止打印功能.我已经做到了-

i want to print number after every n number of seconds and based on few conditions i am changing the timer as well as i am stopping the print function. i have done like this --

var myfunc = {
    value   : 1,
    running : false,
    timer   : 1000,
    start   : function(){
        this.running = true;
        clearInterval(this.timeout);
        this.timeout = setTimeout(function() {
            myfunc.execute(myfunc);
        }, myfunc.timer);

    },
    execute : function(){
        if(!this.running) return false;

        console.log( 'Currently at -- ' + (this.value++) );

        if (this.value > 5 ){
            this.changetiming();
        }

        if (this.value > 10 ){
            this.stop();
            return;
        }else{
            this.start();
        }

    },
    changetiming : function(){
        this.timer = 3000;
    },
    stop : function(){
        this.running = false;
        clearTimeout(this.timeout);
    }
};

myfunc.start();

现在我想知道以下代码有什么问题-

Now i want to know what is wrong with following code --

for(var i = 0; i <= 10; i++){
    print(i);
}


function print(i){
    setTimeout(function(){
        console.log(i)
    },2000);
}

推荐答案

这是在ES6中执行此操作的正确方法和简便方法:

here is the right way and easy way to do this in ES6 :

const printNumbersForEvery2Sec = (n)=>{
  for (let i = 1; i <= n; i++) {
      setTimeout( () =>{
        console.log(i)
      }, i * 2000)
    }
}
printNumbersForEvery2Sec(10);

乘以i,每个setTimeout()分别延迟2到20秒(2000 x 1,2000 x 2…).

by multiplying i , each setTimeout() to be delayed 2 to 20 seconds (2000 x 1, 2000 x 2…) respectively.

这篇关于每2秒打印一次从1到10的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆