柠檬墨绿色 发表于 2016/11/9 14:31

微信小程序 倒计时组件实现代码

  分步骤-性子急的朋友,可以直接看最后那段代码。

  wxml文件放个text

  <text>second: {{second}} micro second:{{micro_second}}</text>

  在js文件中调用

  ?

  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

  function countdown(that) {

  var second = that.data.second

  if (second == 0) {

  // console.log("Time Out…");

  that.setData({

  second: "Time Out…"

  });

  return ;

  }

  var time = setTimeout(function(){

  that.setData({

  second: second - 1

  });

  countdown(that);

  }

  ,1000)

  }

  Page({

  data: {

  second: 3

  },

  onLoad: function() {

  countdown(this);

  }

  });

  运行验证下,从10走到1s,然后显示时间到。

  于是继续将毫秒完善,注意毫秒的步长受限于系统的时间频率,于是我们精确到0.01s即10ms

  js

  ?

  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

  /* 秒级倒计时 */

  function countdown(that) {

  var second = that.data.second

  if (second == 0) {

  that.setData({

  second: "Time out!",

  micro_second: "micro_second too."

  });

  clearTimeout(micro_timer);

  return ;

  }

  var timer = setTimeout(function(){

  that.setData({

  second: second - 1

  });

  countdown(that);

  }

  ,1000)

  }

  /* 毫秒级倒计时 */

  // 初始毫秒数,同时用作归零

  var micro_second_init = 100;

  // 当前毫秒数

  var micro_second_current = micro_second_init;

  // 毫秒计时器

  var micro_timer;

  function countdown4micro(that) {

  if (micro_second_current <= 0) {

  micro_second_current = micro_second_init;

  }

  micro_timer = setTimeout(function(){

  that.setData({

  micro_second: micro_second_current - 1

  });

  micro_second_current--;

  countdown4micro(that);

  }

  ,10)

  }

  Page({

  data: {

  second: 2,

  micro_second: micro_second_init

  },

  onLoad: function(www.9ask.cn/shangqiu/) {

  countdown(this);

  countdown4micro(this);

  }

  });
页: [1]
查看完整版本: 微信小程序 倒计时组件实现代码