【前端】一个简单的倒计时函数

【前端】一个简单的倒计时函数

一个通用的倒计时函数:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
;(function(root, factory) {
  if (typeof module === 'object' && module && module.exports) {
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else {
    root.countdown = factory();
  }
}(this, function() {

  function countdown(seconds, onTicktock, onOver) {
    if (seconds <= 0) {
      console.error('[countdown Error] #1 argument must be greater than 0');
      return null;
    }

    if (typeof onTicktock != 'function') {
      console.error('[countdown Error] #2 argument must be a function');
      return null;
    }

    //倒计时剩余时间
    var restof = seconds;

    //计时器
    var timer = null;

    //计时器间隔
    var intervalTime = 1000;

    function ticktock () {
      if (restof > -1) { // 0 也会返回
        onTicktock(restof--, stop);
      } else {
        stop();
      }
    }

    function stop () {
      clearInterval(timer);
      timer = null;
      onOver && typeof onOver == 'function' && onOver();
    }

    //先执行一次
    ticktock();
    timer = setInterval(function () {
      ticktock();
    }, intervalTime);

    return stop;
  }

  return countdown;
}));

使用:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function t (sec, stop) {
    console.log('剩余:' + sec + '秒');
}

function s () {
    console.log('倒计时结束');
}
var callStop = countdown(5, t, s);

//console
VM366:2 剩余:5
VM366:2 剩余:4
VM366:2 剩余:3
VM366:2 剩余:2
VM366:2 剩余:1
VM366:2 剩余:0
VM366:6 倒计时结束