Форум программистов, компьютерный форум, киберфорум
jQuery
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.92/13: Рейтинг темы: голосов - 13, средняя оценка - 4.92
Эдуардо
1

Цикл таймера обратного отсчета

14.04.2014, 16:03. Показов 2558. Ответов 1
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Привет, друзья!
Помогите зациклить таймер обратного отсчета.
Сейчас счетчик выставляется вручную и отматывает до 0, затем сам переключается на осчитывание 100
дней и отсчет начинается заново при каждом обновлении страницы (F5)
Необходимо просто заменить function, но моих мозгов пока не хватает( Хоть мне это и интересно.


Java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
(function (factory) {
    if (typeof exports === 'object') {
        // CommonJS (Node)
        var jQuery = require('jquery');
        module.exports = factory(jQuery || $);
    } else if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else {
        // globals
        factory(jQuery || $);
    }
}(function ($) {
 
    var methods = {
        start: function(sec){
            if(sec) init.call(this, sec);
            var me = this,
                intervalId = setTimeout(function(){ tick.call(me); }, 1000);
 
            // save start time
            this.data('ttStartTime', (new Date()).getTime());
            this.data('intervalId', intervalId);
        },
 
        stop: function(){
            var data = this.data();
 
            if(data.intervalId){
                clearTimeout(data.intervalId);
                this.data('intervalId', null);
            }
            return data;
        },
        
        reset: function(sec){
            var data = methods.stop.call(this);
 
            this.find('div').css({ backgroundPosition: 'left center' });
            this.find('ul').parent().removeClass('timeTo-alert');
 
            if(typeof sec === "undefined") { sec = data.value; }
            if (data.vals) { data.vals = null; }
            init.call(this, sec);
        }
 
    };
    
    var dictionary = {
        en:{days:"days", hours:"hours", min:"minutes", sec:"seconds"},
        ru:{days:"дней", hours:"часов", min:"минут", sec:"секунд"},
        ua:{days:"днiв", hours:"годин", min:"хвилин", sec:"секунд"},
        de:{days:"Tag", hours:"Uhr", min:"Minuten", sec:"Secunden"},
        fr:{days:"jours", hours:"heures", min:"minutes", sec:"secondes"},
        sp:{days:"dias", hours:"reloj", min:"minutos", sec:"segundos"},
        it:{days:"giorni", hours:"ore", min:"minuti", sec:"secondi"},
        nl:{days:"dagen", hours:"uren", min:"minuten", sec:"seconden"},
        no:{days:"dager", hours:"timer", min:"minutter", sec:"sekunder"},
        pt:{days:"dias", hours:"horas", min:"minutos", sec:"segundos"}
    };
    
    if(typeof $.support.transition === 'undefined'){
        $.support.transition = (function(){
            var thisBody = document.body || document.documentElement,
                thisStyle = thisBody.style,
                support = thisStyle.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined;
 
            return support;
        })();
    }
    
    $.fn.timeTo = function(){
        var defaults = {
                callback: null,          // callback function for exec when timer out
                captionSize: 0,          // font-size by pixels for captions, if 0 then calculate automaticaly
                countdown: true,         // is countdown or real clock
                countdownAlertLimit: 10, // limit in seconds when display red background
                displayCaptions: false,  // display captions under digit groups
                displayDays: 0,          // display day timer, count of days digits
                displayHours: true,      // display hours
                fontFamily: "Verdana, sans-serif",
                fontSize: 28,            // font-size of a digit by pixels
                lang: 'ru',              // language of caption
                seconds: 0,              // timer's countdown value in seconds
                start: true,             // true to start timer immediately
                theme: "white",          // 'white' or 'black' theme fo timer's view
                
                vals: [0, 0, 0, 0, 0, 0, 0, 0, 0],  // private, current value of each digit
                limits: [9, 9, 9, 2, 9, 5, 9, 5, 9],// private, max value of each digit
                iSec: 8,            // private, index of second digit
                iHour: 4,           // private, index of hour digit
                tickTimeout: 1000,  // timeout betweet each timer tick in miliseconds
                intervalId: null    // private
            },
            method, options = {};
 
        for(var i = 0, arg; arg = arguments[i]; ++i){
            if(i == 0 && typeof arg === "string"){
                method = arg;
            }else{
                if(typeof arg == "object"){
                    if(typeof arg.getTime === 'function'){
                        options.timeTo = arg;
                    }else {
                        options = $.extend(options, arg);
                    }
                }else{
                    if(typeof arg == "function"){
                        options.callback = arg;
                    }else{
                        var v = parseInt(arg);
                        if(!isNaN(v)){
                            options.seconds = v;
                        }
                    }
                }
            }
        }
        // set time for countdown to
        if(options.timeTo){
            var time,
                now = (new Date()).getTime();
 
            if(options.timeTo.getTime){ // set time as date object
                time = options.timeTo.getTime();
            }else if(typeof options.timeTo === 'number'){  // set time as integer in millisec
                time = options.timeTo;
            }
            if(options.timeTo > now){
                options.seconds = Math.floor((time - now) / 1000);
            }
        }else if(options.time || !options.seconds){
            var time = options.time;
 
            if(!time) time = new Date();
 
            if(typeof time === 'object' && time.getTime){
                options.seconds = time.getHours()*3600 + time.getMinutes()*60 + time.getSeconds();
                options.countdown = false;
            }else if(typeof time === 'string'){
                var tt = time.split(':'),
                    sec = 0, m = 1, t;
 
                while(t = tt.pop()){
                    sec += t*m;
                    m *= 60;
                }
                options.seconds = sec;
                options.countdown = false;
            }
        }
        if(options.countdown !== false && options.seconds > 86400 && typeof options.displayDays === 'undefined') {
            var days = Math.floor(options.seconds / 86400);
            options.displayDays = days < 10 && 1 || days < 100 && 2 || 3;
        }else if(options.displayDays === true) {
            options.displayDays = 3;
        }else if(options.displayDays) {
            options.displayDays = options.displayDays > 0 ? Math.floor(options.displayDays) : 3;
        }
 
        
        return this.each(function(){
            var $this = $(this),
                data = $this.data(),
                i;
 
            if(!data.vals){ // new clock
                data = $.extend(defaults, options);
                data.height = Math.round(data.fontSize*100/93);
                data.width = Math.round(data.fontSize*.8 + data.height*.13);
                data.displayHours = !!(data.displayDays || data.displayHours);
                $this
                    .addClass('timeTo')
                    .addClass('timeTo-'+ data.theme)
                    .css({
                        fontFamily: data.fontFamily,
                        fontSize: data.fontSize +'px'
                    });
 
                var left = Math.round(data.height / 10),
                    ulhtml = '<ul style="left:'+ left +'px; top:-'+ data.height +'px"><li>0</li><li>0</li></ul></div>',
                    style = ' style="width:'+ data.width +'px; height:'+ data.height +'px;"',
                    dhtml1 = '<div class="first"'+ style +'>'+ ulhtml,
                    dhtml2 = '<div'+ style +'>'+ ulhtml,
                    dot2 = '<span>:</span>',
                    maxWidth = Math.round(data.width * 2 + 3),
                    captionSize = data.captionSize || Math.round(data.fontSize * 0.43);
                    thtml = (data.displayCaptions ?
                        (data.displayHours
                            ? '<figure style="max-width:'+ maxWidth +'px">$1<figcaption style="font-size:'+ captionSize +'px">'+ dictionary[data.lang].hours +'</figcaption></figure>'+ dot2
                            : '') +
                        '<figure style="max-width:'+ maxWidth +'px">$1<figcaption style="font-size:'+ captionSize +'px">'+ dictionary[data.lang].min +'</figcaption></figure>'+ dot2 +
                        '<figure style="max-width:'+ maxWidth +'px">$1<figcaption style="font-size:'+ captionSize +'px">'+ dictionary[data.lang].sec +'</figcaption></figure>'
                        : (data.displayHours ? '$1'+ dot2 : '') +'$1'+ dot2 +'$1'
                    ).replace(/\$1/g, dhtml1 + dhtml2);
 
                if(data.displayDays > 0){
                    var marginRight = data.fontSize * 0.4,
                        dhtml = dhtml1;
                    for(i = data.displayDays - 1; i > 0; i--) {
                        dhtml += i === 1 ? dhtml2.replace('">', ' margin-right:'+ Math.round(marginRight) +'px">') : dhtml2;
                    }
                    thtml = (data.displayCaptions ?
                        '<figure style="width:'+ Math.round(data.width*data.displayDays + marginRight + 4) +'px">$1<figcaption style="font-size:'+ captionSize +'px; padding-right:'+ Math.round(marginRight) +'px">'+ dictionary[data.lang].days +'</figcaption></figure>'
                        : '$1').replace(
                            /\$1/, dhtml
                        ) + thtml;
                }
                $this.html(thtml);
            }else{ // exists clock
                if(data.intervalId){
                    clearInterval(data.intervalId);
                    data.intervalId = null;
                }
                $.extend(data, options);
            }
            
            var $digits = $this.find('div');
 
            if($digits.length < data.vals.length){
                var dif = data.vals.length - $digits.length,
                    vals = data.vals, limits = data.limits;
 
                data.vals = [];
                data.limits = [];
                for(i = 0; i < $digits.length; i++){
                    data.vals[i] = vals[dif + i];
                    data.limits[i] = limits[dif + i];
                }
                data.iSec = data.vals.length - 1;
                data.iHour = data.vals.length - 5;
            }
            data.sec = data.seconds;
            $this.data(data);
            
            if(method && methods[method]){
                methods[ method ].call($this, data.seconds);
            }else if(data.start){
                methods.start.call($this, data.seconds);
            }else {
                init.call($this, data.seconds);
            }
        });
    };
 
    function init(sec){
        var data = this.data(),
            $digits = this.find('ul');
 
        if (!data.vals || $digits.length === 0) return;
 
        if(!sec) sec = data.seconds;
 
        var isInterval = false;
        if (data.intervalId) {
            isInterval = true;
            clearTimeout(data.intervalId);
        }
 
        var days = Math.floor(sec / 86400),
            rest = days * 86400,
            h = Math.floor((sec - rest) / 3600);
 
        rest += h * 3600;
 
        var m = Math.floor((sec - rest) / 60);
        
        rest += m * 60;
        
        var s = sec - rest,
            str = (days < 100 ? '0' + (days < 10 ? '0' : '') : '') + days + (h < 10 ? '0' : '') + h + (m < 10 ? '0' : '') + m + (s < 10 ? '0' : '') + s;
 
        for (var i = data.vals.length - 1, j = str.length - 1, v; i >= 0; i--, j--) {
            v = parseInt(str.substr(j, 1));
            data.vals[i] = v;
            $digits.eq(i).children().html(v);
        }
        if (isInterval) {
            var me = this;
            data.ttStartTime = Date.now();
            data.intervalId = setTimeout(function(){ tick.call(me); }, 1000);
            this.data('intervalId', data.intervalId);
        }
    }
        
    /**
     * Switch specified digit by digit index
     * @param {number} - digit index
     */
    function tick(digit) {
        var $digits = this.find('ul'),
            data = this.data();
 
        if (!data.vals || $digits.length == 0){
            if(data.intervalId){
                clearTimeout(data.intervalId);
                this.data('intervalId', null);
            }
            if(data.callback) data.callback();
 
            return;
        }
        if (digit == undefined) {
            digit = data.iSec;
        }
 
        var n = data.vals[digit],
            $ul = $digits.eq(digit),
            $li = $ul.children(),
            step = data.countdown ? -1 : 1;
 
        $li.eq(1).html(n);
        n += step;
 
        if(digit == data.iSec){
            var tickTimeout = data.tickTimeout,
                timeDiff = (new Date()).getTime() - data.ttStartTime;
 
            data.sec += step;
 
            tickTimeout += Math.abs(data.seconds - data.sec) * tickTimeout - timeDiff;
 
            data.intervalId = setTimeout(function(){ tick.call(me); }, tickTimeout);
        }
        
        if(n < 0 || n > data.limits[digit]) {
            if(n < 0)
            {
                n = data.limits[digit];
                if(digit == data.iHour && data.displayDays > 0 && digit > 0 && data.vals[digit-1] == 0) // fix for hours when day changing
                    n = 3;
            }
            else 
                n = 0;
            if(digit > 0){
                tick.call(this, digit-1);
            }
        }
        //$ul.removeClass('transition');
        //$ul.css({top:"-" + data.height + "px"});
        $li.eq(0).html(n);
        
        var me = this;
        
        if($.support.transition){
            $ul.addClass('transition');
            $ul.css({top:0});
 
            setTimeout(function(){
                $ul.removeClass('transition');
                $li.eq(1).html(n);
                $ul.css({top:"-"+ data.height +"px"});
 
                if(step > 0 || digit != data.iSec) return;
 
                if(data.sec == data.countdownAlertLimit){
                    $digits.parent().addClass('timeTo-alert');
                }
                if(data.sec === 0){
                    $digits.parent().removeClass('timeTo-alert');
 
                    if(data.intervalId){
                        clearTimeout(data.intervalId);
                        me.data('intervalId', null);
                    }
 
                    if(typeof data.callback === 'function') data.callback();
                }
            }, 410);
        }else{
            $ul.stop().animate({top:0}, 400, digit != data.iSec ? null : function(){
                $li.eq(1).html(n);
                $ul.css({top:"-"+ data.height +"px"});
                if(step > 0 || digit != data.iSec) return;
 
                if(data.sec == data.countdownAlertLimit){
                    $digits.parent().addClass('timeTo-alert');
                }else if(data.sec == 0){
                    $digits.parent().removeClass('timeTo-alert');
 
                    if(data.intervalId){
                        clearTimeout(data.intervalId);
                        me.data('intervalId', null);
                    }
 
                    if(typeof data.callback === 'function') data.callback();
                }
            });
        }
        data.vals[digit] = n;
        //this.data('vals', data.vals);
    }
 
    return jQuery;
    
}));
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
14.04.2014, 16:03
Ответы с готовыми решениями:

Таймер обратного отсчета
Здравствуйте. Делаю таймер, использую плагин ФлипКоунт. Вопрос: что нужно вставить в переменную t,...

Таймер обратного отсчёта
У меня возникла проблема с реализацией работы таймера. Во-первых, у меня не получается...

Таймер обратного отсчета
Доброго времени суток, хочу сделать что-то вроде таймера. Есть число 10000 и 100, и хочу чтоб был...

Таймер обратного отсчета
Подскажите что нужно дописать, что таймер автоматом каждые сутки в 00:00 добавлял время+1 день и...

1
2 / 2 / 2
Регистрация: 31.10.2013
Сообщений: 66
14.04.2014, 17:27 2
Лучший ответ Сообщение было отмечено как решение

Решение

Не ужели 400строк нужно? Я вам немного подскажу:
Узнаем время в секундах от 70-года года до (к примеру) 15апреля этого, потом до сегодняшней даты(заносим оба значения в переменные). Вычитаем из первой переменной вторую. Теперь самое интересное: чтобы получить время в формате чч:мм:сс
Javascript
1
2
3
4
Var time;
Var hour = time/60/60%24;
Var minute = time/60%60;
Var sec = time%60;
Сори что не очень подробно(я с планшета пишу), но вы думаю поняли

Добавлено через 10 минут
P.S. я к тому что легче написать самому чем копаться в чужом коде
0
14.04.2014, 17:27
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
14.04.2014, 17:27
Помогаю со студенческими работами здесь

Редактирование скрипта обратного отсчета
Помогите пожалуйста, пытаюсь разобраться уже битый час, так как сам не программист, сложно. Есть...

JavaScript таймер обратного отсчёта
Доброго времени суток Подскажите как сделать. чтобы разница var_timer всегда была равна пяти...

Скрипт обратного отсчета времени
Добрый день. Подскажите, пожалуйста, вот у меня есть кодовый скрипт отсчета времени на сайте....

Таймер обратного отсчета 5 минут
Всем привет, помоги пожалуйста изменить код так, что бы убрать часы, а оставить лишь минуты и...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru