小程序模板网

微信小程序电商常用倒计时

wxml文件放个text

second: {{second}} micro second:{{micro_second}}

在js文件中调用

 

				
  1. function countdown(that) {
  2. var second = that.data.second
  3. if (second == 0) {
  4. // console.log("Time Out...");
  5. that.setData({
  6. second: "Time Out..."
  7. });
  8. return ;
  9. }
  10. var time = setTimeout(function(){
  11. that.setData({
  12. second: second - 1
  13. });
  14. countdown(that);
  15. }
  16. ,1000)
  17. }
  18.  
  19. Page({
  20. data: {
  21. second: 3
  22. },
  23. onLoad: function() {
  24. countdown(this);
  25. }
  26. });

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

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

js

 

				
  1. /* 秒级倒计时 */
  2. function countdown(that) {
  3. var second = that.data.second
  4. if (second == 0) {
  5. that.setData({
  6. second: "Time out!",
  7. micro_second: "micro_second too."
  8. });
  9. clearTimeout(micro_timer);
  10. return ;
  11. }
  12. var timer = setTimeout(function(){
  13. that.setData({
  14. second: second - 1
  15. });
  16. countdown(that);
  17. }
  18. ,1000)
  19. }
  20.  
  21. /* 毫秒级倒计时 */
  22. // 初始毫秒数,同时用作归零
  23. var micro_second_init = 100;
  24. // 当前毫秒数
  25. var micro_second_current = micro_second_init;
  26. // 毫秒计时器
  27. var micro_timer;
  28.  
  29. function countdown4micro(that) {
  30. if (micro_second_current <= 0) {
  31. micro_second_current = micro_second_init;
  32. }
  33. micro_timer = setTimeout(function(){
  34. that.setData({
  35. micro_second: micro_second_current - 1
  36. });
  37. micro_second_current--;
  38. countdown4micro(that);


易优小程序(企业版)+灵活api+前后代码开源 码云仓库:starfork
本文地址:https://www.eyoucms.com/wxmini/doc/course/23770.html 复制链接 如需定制请联系易优客服咨询:800182392 点击咨询
QQ在线咨询