Форум Flasher.ru

Форум Flasher.ru (http://www.flasher.ru/forum/index.php)
-   ActionScript 1.0/2.0 (http://www.flasher.ru/forum/forumdisplay.php?f=93)
-   -   как сделать нормальный таймер? (http://www.flasher.ru/forum/showthread.php?t=116870)

bootaka 13.10.2008 08:38

как сделать нормальный таймер?
 
вопрос наибанальнейший. Я сделал таймер:
Код:

onClipEvent (load) {
        TimeSec = 0;
        secs = 0;
        mins = 0;
}
onClipEvent (enterFrame) {
        TimeSec = Number(TimeSec+1);
        if (TimeSec == 30) {
                TimeSec = 0;
                secs = Number(secs+1);
                _root.sec.text = secs;
        }
}

скорость кадров - 30 FPS. то есть таймер прибавляет каждую 1/30-ю секунды по 1, а потом, после 1 сек., прибавляет по 1 в текстовое поле. Но показания таймера зависят от реальной скорости кадров. как сделать таймер, "независимый" от фактической скорости кадров???????
ЗЫ ночами не сплю, аппетит потерял, заболел, захандрил, так сильно ответ нужен... :(:(:(

iNils 13.10.2008 09:36

Использовать класс Date или функцию getTimer ()
А для оформления своего кода, надо использовать теги [code][/code], а не [quote][/quote].

zanull 13.10.2008 14:28

пример таймера с запуском и остановкой:

Код:

Timer = function(start){
        this.reset(start);
}
Timer.prototype.start = function(){
        if (this._pauseTime){
                this._startTime += getTimer() - this._pauseTime;
                this._pauseTime = 0;
        }else{
                this.reset(true);
        }
}
Timer.prototype.stop = function(){
        if (!this._pauseTime) this._pauseTime = getTimer();
}
Timer.prototype.reset = function(restart){
        this._startTime = getTimer();
        if (!this._startTime) this._startTime = 1;
        if (restart) this._pauseTime = 0;
        else this._pauseTime = this._startTime;
}

Timer.prototype.getTime = function(){
        if (this._pauseTime) return this._pauseTime - this._startTime;
        var gotTime = getTimer();
        if (!gotTime) gotTime = 1;
        return gotTime - this._startTime;
}
Timer.prototype.setTime = function(t){
        this._startTime = getTimer() - t;
}
Timer.prototype.addProperty("time",Timer.prototype.getTime,Timer.prototype.setTime);

Timer.prototype.getPaused = function(){
        return (this._pauseTime) ? true : false;
}
Timer.prototype.setPaused = function(p){
        if (p == Boolean(this._pauseTime)) return false;
        if (p) this.stop();
        else this.start();
}
Timer.prototype.addProperty("paused",Timer.prototype.getPaused,Timer.prototype.setPaused);

function formatTime(milliseconds){
        var centiseconds = Math.floor(milliseconds/10);
        var seconds = Math.floor(centiseconds/100);
        var minutes = Math.floor(seconds/60);
       
        centiseconds %= 0;
        seconds %= 60;
        minutes %= 60;
       
        if (centiseconds < 10) centiseconds = "0" + centiseconds;
        if (seconds < 10) seconds = "0" + seconds;
        if (minutes < 10) minutes = "0" + minutes;
       
        return minutes +":"+ seconds +""+ centiseconds;
}


var clock_timer = new Timer();
clock_timer.start();


this.onEnterFrame = function(){
        display_txt.text = formatTime(clock_timer.time);
}

stop_btn.onRelease = function(){
        clock_timer.stop();
}

play_btn.onRelease = function(){
        if (clock_timer.paused) clock_timer.start(); // only start if paused
}

display_txt - имя текстового поля

Xero201 14.10.2008 00:56

А вот моё скромное творение :rolleyes:

Код самого таймера (timer.swf)

Код:

s=0;
//если время не равно нулю, можно подставить любое другое значение
m_time_txt.text = 0; //динамическое текстовое поля для минут
s_time_txt.text = 0;  //для секунд
stop();
setInterval(function(){
if(_global.res_time){ //проверка запущен ли таймер
s++;

        if((s/60) == 1)
        {
        s = 0;
        m_time_txt.text = Number(m_time_txt.text)+1;
        }
                s_time_txt.text = s;
}
                                }
,1000)
;

И код клипа в котором этот таймер можно запустить (start_timer.swf)
Код:

this.createEmptyMovieClip("timer_place_mc",getNextHighestDepth());        //создает пустой клип для загрузки часов
this.timer_place_mc.loadMovie("timer.swf");        //загружает в него внешний swf-фильм с часами
this.timer_place_mc._x= 120;                //позиционирует часы по оси Ох
this.timer_place_mc._y= 120;                //позиционирует часы по оси Ох
_global.res_time  = 1; //запускаем таймер,                _global.res_time  = 0;        -остонавливает

Но если ты (to bootaka) просто хочешь заменить "enterFrame" то вот синтаксис используемой мной функции
setInterval(function(){ //..твоя функция..},time);
где time - количество миллисекунд через которые нужно выполнять функцию, в данном случае 1000 (т.е. 1 секунда).

bootaka 14.10.2008 07:46

!!!!!!!! спасибище! Всё работает!
(хотел сказать "как всё было просто", но пальцы не повернулись)


Часовой пояс GMT +4, время: 10:35.

Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.