WeChat Mini Program - Countdown
The realization of the countdown component of the WeChat applet, the function is suitable for the limited-time group purchase of e-commerce applications, the second-kill of goods, etc.
/** * A target date is required. When initializing, first get how many seconds are left to the current time * 1. Change the seconds to formatted output as XX days XX hours XX minutes XX seconds XX * 2. Provide a clock, run every 10ms, render the clock, and then decrement the total ms by 10 * 3. When the remaining seconds are zero, return, and give tips that it has expired */ // Define a total number of milliseconds, take ten hours as an example. var total_micro_second = 36000 * 1000; // millisecond countdown function count_down(that) { that.setData({ clock : date_format(total_micro_second) }); if (total_micro_second <= 0) { that.setData({ clock : "Time has expired" }); return } setTimeout(function(){ total_micro_second -= 10; count_down(that); },10) } // Time formatted output, eg: 09:59:19 86. will be called every 10ms function date_format(micro_second) { var second = Math.floor(micro_second / 1000); var hr = Math.floor (second / 3600); var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60)); var sec = fill_zero_prefix((second - hr * 3600 - min * 60)); var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10)); return hr + ":" + min + ":" + sec + " " + micro_sec; } // fill with zeros if the number of digits is insufficient function fill_zero_prefix(num) { return num < 10 ? "0" + num : num } Page({ data: { clock: '' }, onLoad: function() { count_down(this); } });
<text style="display:block;text-align:center;font-size:30px;color:#f60;"> {{clock}} </text>