setInterval(function(),time) change time on runtime

后端 未结 6 1314
粉色の甜心
粉色の甜心 2020-12-11 04:08

I want to change setInterval function time when my code is running.

I try this



        
6条回答
  •  萌比男神i
    2020-12-11 04:14

    this is mi example, i think is more simple and easy to understand

    const timer = {
      time: 5, // 5 time in seconds
      _time: null,
      _timeout: null,
      fun: () => {},
      start() {
        if (this._timeout == null) {
          const self = this;
          this.fun();
          this._timeout = setTimeout(function repeater() {
            self.fun();
            self._timeout = setTimeout(repeater, 1000 * self.time);
          }, 1000 * this.time);
        }
      },
      stop() {
        const timeout = this._timeout;
        this._timeout = null;
        this.set_time(); // set time to default
        clearTimeout(timeout);
      },
      set_time(time) {
        if (this._time == null) this._time = this.time;
    
        if (time) {
          this.time = time;
        } else {
          this.time = this._time;
        }
      },
    };
    

    Explication:

    • time: is the time of interval between every iteration, cycle or next call
    • _time: this variable save the default value of time, when use stop(), this variable(_time) restore "time"
    • start: this function start the iteration, if you call again, it will not duplicate.
    • stop: this function, stop the timeout and set default time and _timeout
    • set_time: this function set a new value to time, if you not send a parameter, time restore to default value, declare on running in this example is "5"

    example:

    const timer = {
          time: 5, // 5 time in seconds
          _time: null,
          _timeout: null,
          fun: () => {},
          start() {
            if (this._timeout == null) {
              const self = this;
              this.fun();
              this._timeout = setTimeout(function repeater() {
                self.fun();
                self._timeout = setTimeout(repeater, 1000 * self.time);
              }, 1000 * this.time);
            }
          },
          stop() {
            const timeout = this._timeout;
            this._timeout = null;
            this.set_time(); // set time to default
            clearTimeout(timeout);
          },
          set_time(time) {
            if (this._time == null) this._time = this.time;
        
            if (time) {
              this.time = time;
            } else {
              this.time = this._time;
            }
          },
        };
        
    // print time
    timer.fun = () =>{
        console.log(new Date())
    };
    timer.set_time(10)
    timer.start()

提交回复
热议问题