Javascript停止&启动控制台日志

时间:2017-05-26 19:22:27

标签: javascript

我试图完成一个要求的挑战。

创建一个将消息和数字作为参数的函数,并将消息按时间记录到控制台。



var displayLog = function Container(param) {
  var message = 'any string'; // Local message variable
  var timeCount = '10'; // Local time count variable

  setInterval(function getLoggeddemo(message, timeCount) {
    console.log(message);
    return getLoggeddemo;
  }(), timeCount);

  function myStopFunction() {
    clearInterval(myVar);
  };
}



var mixBut = document.getElementById("mixBut");

mixBut.addEventListener("click", Start);

function Start() {
  displayLog.setInterval();
}

function Stop() {
  displayLog.myStopFunction();
}

<input type="button" id="mixBut" value="Start" />
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

var displayLog  = {

    message : 'any string', // Default local message variable

    timeCount : 1000, // Default local time count variable => equal to 1second

    myVar : undefined, //at first is undefined,see myStartFunction

    setSeconds : function(number_of_seconds){
         this.myStopFunction();//first stop previously event if existing 
         this.timeCount = number_of_seconds * 1000;
    },

    setMessage : function(message){
         this.message= message;
    },

    myStartFunction : function(){
         this.myVar=setInterval(function(){
               console.log(displayLog.message);
          }, displayLog.timeCount);
    },
    myStopFunction:function(){
        clearInterval(this.myVar);
    }
 }

 var mixBut = document.getElementById("mixBut");
 var c = 0;
 mixBut.addEventListener("click", toggleStartStop);

 function toggleStartStop(){
     if(c%2==0)
           displayLog.myStartFunction();
     else 
           displayLog.myStopFunction();
     c++;
 }