Chronometer in JS

Asked

Viewed 7,788 times

2

Guys I made a stopwatch on JS but it "Treme" when I run it, is there any way to fix it ?

var centesimas = 0;
var segundos = 0;
var minutos = 0;
var horas = 0;
function inicio () {
    control = setInterval(cronometro,10);
    document.getElementById("inicio").disabled = true;
    document.getElementById("parar").disabled = false;
    document.getElementById("continuar").disabled = true;
    document.getElementById("reinicio").disabled = false;
}
function parar () {
    clearInterval(control);
    document.getElementById("parar").disabled = true;
    document.getElementById("continuar").disabled = false;
}
function reinicio () {
    clearInterval(control);
    centesimas = 0;
    segundos = 0;
    minutos = 0;
    horas = 0;
    Centesimas.innerHTML = ":00";
    Segundos.innerHTML = ":00";
    Minutos.innerHTML = ":00";
    Horas.innerHTML = "00";
    document.getElementById("inicio").disabled = false;
    document.getElementById("parar").disabled = true;
    document.getElementById("continuar").disabled = true;
    document.getElementById("reinicio").disabled = true;
}
function cronometro () {
    if (centesimas < 99) {
        centesimas++;
        if (centesimas < 10) { centesimas = "0"+centesimas }
        Centesimas.innerHTML = ":"+centesimas;
    }
    if (centesimas == 99) {
        centesimas = -1;
    }
    if (centesimas == 0) {
        segundos ++;
        if (segundos < 10) { segundos = "0"+segundos }
        Segundos.innerHTML = ":"+segundos;
    }
    if (segundos == 59) {
        segundos = -1;
    }
    if ( (centesimas == 0)&&(segundos == 0) ) {
        minutos++;
        if (minutos < 10) { minutos = "0"+minutos }
        Minutos.innerHTML = ":"+minutos;
    }
    if (minutos == 59) {
        minutos = -1;
    }
    if ( (centesimas == 0)&&(segundos == 0)&&(minutos == 0) ) {
        horas ++;
        if (horas < 10) { horas = "0"+horas }
        Horas.innerHTML = horas;
    }
}
*{
    margin: 0;
    padding: 0;
}
body {
    background-color: #ffae00;
}
.reloj{
    font-size: 170%;
    font-family: 'Orbitron', sans-serif;
    color: #363431;
    display: inline-block;
    float: left;
    margin-top: 50%;
}
.boton{
    margin: 2%;
    display: inline-block;
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;
    box-sizing: content-box;
    float: none;
    z-index: auto;
    width: auto;
    height: auto;
    position: relative;
    cursor: pointer;
    opacity: 1;
    top: 0;
    padding: 0 22px;
    overflow: visible;
    border: 4px solid rgb(255,255,255);
    -webkit-border-radius: 0;
    border-radius: 0;
    font: normal normal bold 50px/50px Arial, Helvetica, sans-serif;
    color: rgb(255, 255, 255);
    text-align: center;
    text-transform: uppercase;
    -o-text-overflow: clip;
    text-overflow: clip;
    background: #FFAE00;
    -webkit-box-shadow: none;
    box-shadow: none;
    text-shadow: none;
    -webkit-transition: none;
    -moz-transition: none;
    -o-transition: none;
    transition: none;
    -webkit-transform: none;
    transform: none;
    -webkit-transform-origin: 50% 50% 0;
    transform-origin: 50% 50% 0;
}
.boton:hover{
    margin: 2%;
    display: inline-block;
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;
    box-sizing: content-box;
    float: none;
    z-index: auto;
    width: auto;
    height: auto;
    position: relative;
    cursor: pointer;
    opacity: 1;
    top: 0;
    padding: 0 22px;
    overflow: visible;
    border: 4px solid rgb(255,255,255);
    -webkit-border-radius: 0;
    border-radius: 0;
    font: normal normal bold 50px/50px Arial, Helvetica, sans-serif;
    color: #FFAE00;
    text-align: center;
    text-transform: uppercase;
    -o-text-overflow: clip;
    text-overflow: clip;
    background: #ffffff;
    -webkit-box-shadow: none;
    box-shadow: none;
    text-shadow: none;
    -webkit-transition: none;
    -moz-transition: none;
    -o-transition: none;
    transition: none;
    -webkit-transform: none;
    transform: none;
    -webkit-transform-origin: 50% 50% 0;
    transform-origin: 50% 50% 0;
}
#crono {
    margin-top: 0%;
    width: 160%;
    margin-right: -30%;
    float: right;
    display: inline-block;
}

#numeros{
    margin-top:10%;
}

#contador{
    position: absolute;
    margin-top: 32%;
    left: 19%;
}
#botoes{
    position: absolute;
    margin-top: 120%;
    left: 10%;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>cronometro</title>
        <link rel="stylesheet" href="css/cronometro.css">
        <script type="text/javascript" src="js/cronometro.js"></script>
        <link href="https://fonts.googleapis.com/css?family=Open+Sans|Orbitron" rel="stylesheet">     </head>
    <body>
        <div id="contador">
            <div class="reloj" id="Horas">00</div>
            <div class="reloj" id="Minutos">:00</div>
            <div class="reloj" id="Segundos">:00</div>
            <div class="reloj" id="Centesimas">:00</div>
        </div>
        <div id="botoes">
            <input type="button" class="boton" id="inicio" value=" &#9658;" onclick="inicio();">
            <input type="button" class="boton" id="parar" value=" &#8718;" onclick="parar();" disabled>
            <input type="button" class="boton" id="continuar" value=" &#8634;" onclick="inicio();" disabled>
            <input type="button" class="boton" id="reinicio" value=" &#8635;" onclick="reinicio();" disabled>
        </div>
       <img id="crono" src="img/cronometro.png" alt="cronometro" title="cronometro flat">


    </body>
</html>

2 answers

1


Change the counter position to relative.

#contador{
    position: relative;
    margin-top: 32%;
    left: 19%;
}

The Absolute position is doing the calculation at all times. Reference: the element with Position Absolute uses the top left of other elements. These elements are his relatives of the element with position Absolute. More specifically his father.

  • Solved. Thank you very much helped a lot.

  • Mark as useful answer, on the arrow next to the top. <

  • 1

    Thanks for the tip. I’m new to the forum.

1

I’m making available here the Chronometror, a javascript object that mounts a stopwatch on your page.

  1. Copy the code below and save to an HTML file
  2. Open the HTML file in a browser
  3. Find the settings that can be applied
  4. Edit the HTML code and copy the 'time object'
  5. Paste the object into a javascript file using a particular page of your application
  6. Create a stopwatch by calling the chronometer method.Create(Parameters) which returns the reference to the stopwatch (as you can create several).
  7. Enter the desired parameters:

    • regressive: bool type, if true the stopwatch counts backwards, if false, starts from scratch and increments (this is the default)
    • seconds: type int, if the stopwatch is regressive are the seconds when the stopwatch starts, from the counter, are the seconds when the stopwatch stops (in which case if the stopwatch is zero the stopwatch does not stop alone)
    • element: DOM element type (those returned with Document.getElementById()), element where the stopwatch will be displayed
    • alert_missing seconds: int type, if you want the stopwatch to be alert when N seconds are missing, enter here. The timer element will receive a class called "alert" and you decide the CSS of that class.
    • start: bool type, indicates if the timer already fires as soon as it is created. To fire later, call the chronometer method.start() passing as parameter the chronometer reference returned in the chronometer method.().
    • ao_finish: type Function, javascript function that runs at the end of the timer time. Take as a parameter the stopwatch reference.
    • funcao_para_mostrar: type Function, javascript function that is executed to generate the timer display. It takes as parameters: element (dom element of the stopwatch), hours, minutes, seconds (all integers) and alert (bool) indicating if the stopwatch is in alert state. The object itself has two ready-to-display methods and you should only write your own method if those that already exist are not suitable for your needs. The methods are: chronometer.mostra Migavel() and chronometer.mostraPadrao(), this being the default, that is, if you do not inform this parameter in the creation of the stopwatch, the default will be assumed.

The methods of the time object to be used are:

create(parameters) - to create a stopwatch, pause (reference) - to pause a stopwatch, start(reference) - to start a stopwatch which is paused, reset(reference) - to reset the timer time, destroy(reference, destrur_element) - to eliminate the stopwatch, with option to delete the stopwatch element

<!doctype>
<html>
    <head>
        <meta charset="utf-8">
        <title>Teste</title>
        <style>
            body
            {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                padding: 0;
                margin: 0;
                font-family: verdana, sans-serif;
            }
            table
            {
                font-size: .8em;
            }
            #titulo
            {
                position: absolute;
                margin: 0;
                padding: 0;
                top: 0;
                left: 0;
                right: 0;
                height: 30px;
                line-height: 30px;
                text-align: center;
                vertical-align: middle;
                font-size: 20px;
                font-weight: bold;
                color: #a567aa;
                background-color: #d3bdd4;
                box-sizing: border-box;
                border-bottom: solid 1px lightgray;
            }
            #formulario
            {
                position: absolute;
                top: 30px;
                left: 0;
                width: 500px;
                bottom: 0;
                overflow: auto;
                box-sizing: border-box;
                border-right: solid 1px lightgray;
                background-color: #e8e8e8;
            }
            #painel_cronometros
            {
                position: absolute;
                top: 30px;
                left: 500px;
                right: 0;
                bottom: 0;
                overflow: auto;
                box-sizing: border-box;
            }
            .cronometro
            {
                font-size: 30px;
                padding: 10px 2px;
                background-color: #d8d8d8;
                margin: 10px 0;
                border: solid 1px #afafaf;
                border-radius: 3px;
                display: inline-block;
            }
            .cronometro_padrao
            {
                color: blue;
            }
            .cronometro_amigavel
            {
                color: darkgreen;
            }
            .alerta
            {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1 id="titulo">
            TESTE DE CRONOMETRO
        </h1>
        <form id="formulario">
            <table style="margin: 20px auto;" cellspacing="0" cellpadding="10" border="0">
                <caption style="font-weight: bold; padding: 10px 0;">opções do cronômetro</caption>
                <tr>
                    <td>
                        <label for="c1">
                            segundos:
                        </label>
                    </td>
                    <td>
                        <input id="c1" type="number" value="10" style="width: 50px;"/>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="c2">
                            alertar_faltando_segundos:
                        </label>
                    </td>
                    <td>
                        <input id="c2" type="number" value="3" style="width: 50px;"/>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="c3">
                            regressivo:
                        </label>
                    </td>
                    <td>
                        <input type="checkbox" id="c3"/> 
                    </td>
                </tr>
                <tr>
                    <td>
                        <label for="c4">
                            iniciar:
                        </label>
                    </td>
                    <td>
                        <input type="checkbox" id="c4" checked/> 
                    </td>
                </tr>
                <tr>
                    <td valign="top">
                        <label for="c5">
                            ao_terminar:
                        </label>
                    </td>
                    <td>
                        <label for="c5" style="font-style: italic;">
                            digite a função javascript
                        </label>
                        <br/>
                        <textarea id="c5" style="width: 200px; height: 100px;">document.getElementById('check_' + i).checked = true;</textarea> 
                    </td>
                </tr>
                <tr>
                    <td valign="top">
                        funcao_para_mostrar:
                    </td>
                    <td>
                        <label>
                            <input type="radio" name="f" id="c6" checked> 
                            cronometror.mostrarPadrao
                        </label>
                        <br/>
                        <label>
                            <input type="radio" name="f" id="c7"> 
                            cronometror.mostrarAmigavel
                        </label>
                        <br/>
                        <label>
                            <input type="radio" name="f" id="c8"> 
                            outro
                        </label>
                        <br/>
                        <label for="c9" style="font-style: italic;">
                            digite a função javascript
                        </label>
                        <br/>
                        <textarea id="c9" style="width: 200px; height: 100px;"></textarea> 
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <input type="button" value="criar" onclick="criarCronometro();"/>
                    </td>
                </tr>
            </table>
        </form>
        <div id="painel_cronometros">
        </div>
    </body>
    <script>
        var cronometror =
            {
                instancias:
                    [],
                intervalo_milisegundos:
                    100,
                interval:
                    null,
                dados_padrao:
                    {
                        segundos: 0,
                        alertar_faltando_segundos: null,
                        regressivo: false,
                        iniciar: true,
                        ao_terminar: null,
                        elemento: null,
                        pausado: true,
                        funcao_para_mostrar: null
                    },
                criar:
                    function(dados)
                    {
                        cronometror.dados_padrao.funcao_para_mostrar = cronometror.mostraPadrao;
                        for (var i in cronometror.dados_padrao)
                        {
                            if (typeof dados[i] == 'undefined')
                            {
                                dados[i] = cronometror.dados_padrao[i];
                            }
                        }
                        dados.segundos_atuais = dados.regressivo ? dados.segundos : 0;
                        dados.segundos_iniciais = 0;
                        dados.tempo_inicio = null;
                        var i = cronometror.instancias.push(dados) - 1;
                        cronometror.mostrar(i);
                        if (dados.iniciar)
                        {
                            cronometror.iniciar(i);
                        }
                        return i;
                    },
                iniciar:
                    function(i)
                    {
                        cronometror.instancias[i].pausado = false;
                        cronometror.zerar(i);
                        cronometror.ativarIntervalo();
                    },
                ativarIntervalo:
                    function()
                    {
                        if (!cronometror.interval)
                        {
                            cronometror.interval = setInterval(cronometror.atualizar, cronometror.intervalo_milisegundos);
                        }
                    },
                pausar:
                    function(i, status)
                    {
                        status = typeof status == 'undefined' ? true : status;
                        with (cronometror.instancias[i])
                        {
                            if (status)
                            {
                                if (!pausado)
                                {
                                    cronometror.setar(i, segundos_iniciais + ((new Date() - tempo_inicio) / 1000));
                                }
                            }
                            else
                            {
                                if (pausado)
                                {
                                    tempo_inicio = new Date();
                                    cronometror.ativarIntervalo();
                                }
                            }
                            pausado = status;
                        }
                    },
                setar:
                    function(i, segundos)
                    {
                        cronometror.instancias[i].segundos_iniciais = segundos;
                    },
                zerar:
                    function(i)
                    {
                        with (cronometror.instancias[i])
                        {
                            tempo_inicio = new Date();
                            segundos_iniciais = 0;
                            segundos_atuais = regressivo ? segundos : 0;
                        }
                        cronometror.mostrar(i);
                    },
                destruir:
                    function(i, destruir_elemento)
                    {
                        if (typeof destruir_elemento != 'undefined' && destruir_elemento)
                        {
                            cronometror.instancias[i].elemento.parentNode.removeChild(cronometror.instancias[i].elemento);
                        }
                        delete cronometror.instancias[i];
                    },
                mostrarPadrao:
                    function(elemento, h, m, s, alerta)
                    {
                        elemento.innerHTML = 
                            '<span class="cronometro cronometro_padrao' + (alerta ? ' alerta' : '') + '">' +
                                (h < 10 ? '0' : '') + h + 
                                ':' +
                                (m < 10 ? '0' : '') + m + 
                                ':' +
                                (s < 10 ? '0' : '') + s;
                            '<span>';
                    },
                mostrarAmigavel:
                    function(elemento, h, m, s, alerta)
                    {
                        elemento.innerHTML = 
                            '<span class="cronometro cronometro_amigavel' + (alerta ? ' alerta' : '') + '">' +
                                (h ? h + 'h' : '') +
                                (m ? (h && m < 10 ? '0' : '') + m + 'm' : '') +
                                (m && s < 10 ? '0' : '') + s + 's';
                            '<span>';
                    },
                mostrar:
                    function(i)
                    {
                        var hs, ms, ss, alerta;
                        with (cronometror.instancias[i])
                        {
                            hs = (segundos_atuais / 3600) | 0;
                            ms = ((segundos_atuais - (hs * 3600)) / 60) | 0;
                            ss = segundos_atuais - (hs * 3600) - (ms * 60);
                            ss = regressivo ? Math.ceil(ss) : Math.floor(ss);
                            alerta =
                                alertar_faltando_segundos ?
                                    (
                                        regressivo ? 
                                            segundos_atuais <= alertar_faltando_segundos 
                                        : 
                                            segundos && segundos - segundos_atuais <= alertar_faltando_segundos
                                    )
                                :
                                    false;
                            funcao_para_mostrar(elemento, hs, ms, ss, alerta, i);
                        }
                    },
                atualizar:
                    function()
                    {
                        var tempo = new Date();
                        for (var i in cronometror.instancias)
                        {
                            with (cronometror.instancias[i])
                            {
                                if (pausado)
                                {
                                    continue;
                                }
                                if (regressivo)
                                {
                                    segundos_atuais = segundos - ((tempo - tempo_inicio) / 1000) - segundos_iniciais;
                                    if (segundos_atuais <= 0)
                                    {
                                        segundos_atuais = 0;
                                        cronometror.pausar(i);
                                        if (typeof ao_terminar == 'function')
                                        {                                      
                                            ao_terminar(i);
                                        }
                                    }
                                }
                                else
                                {
                                    segundos_atuais = ((tempo - tempo_inicio) / 1000) + segundos_iniciais;
                                    if (segundos && segundos_atuais >= segundos)
                                    {
                                        segundos_atuais = segundos;
                                        cronometror.pausar(i);
                                        if (typeof ao_terminar == 'function')
                                        {
                                            ao_terminar(i);
                                        }
                                    }
                                }
                                cronometror.mostrar(i);
                            }
                        }
                    }
            };
        var indice = 0;
        function criarCronometro()
        {
            var elemento = document.createElement('div');
            elemento.id = 'container_cronometro_' + indice;
            elemento.style.padding = '10px';
            elemento.style.borderBottom = 'dashed 1px ligthgray';
            elemento.innerHTML = 
                '<div style="padding-bottom: 10px; border-bottom: dashed 1px #aaaaaa;">' +
                    '<div>' +
                        'Cronômetro ' + indice +
                    '</div>' +
                    '<div id="d_' + indice + '">' +
                        '<div id="cronometro_' + indice + '">' +
                        '</div>' +
                        '<label style="cursor: pointer">' +
                            '<input' + 
                                 ' id="check_' + indice + '"' + 
                                 ' type="checkbox"' + 
                                 ' onchange="cronometror.pausar(' + indice + ', this.checked);"' +
                                 (document.getElementById('c4').checked ? '' : ' checked') +
                            '/> ' + 
                            'pausado' + 
                        '</label>' +
                        '<span style="padding: 0 5px;">' + 
                            '|' +
                        '</span>' +
                        '<a' + 
                            ' style="cursor: pointer"' + 
                            ' onclick="cronometror.zerar(' + indice + ');"' +
                        '>' + 
                            'zerar' + 
                        '</a>' +
                        '<span style="padding: 0 5px;">' + 
                            '|' +
                        '</span>' +
                        '<a' + 
                            ' style="cursor: pointer"' + 
                            ' onclick=' + 
                                '"' + 
                                    "cronometror.destruir(" + indice + ");" + 
                                    "document.getElementById('d_" + indice + "').innerHTML = 'este cronômetro não existe mais';" + 
                                '"' + 
                        '>' + 
                            'destruir' + 
                        '</a>' +
                        '<span style="padding: 0 5px;">' + 
                            '|' +
                        '</span>' +
                        '<a' + 
                            ' style="cursor: pointer"' + 
                            ' onclick=' + 
                                '"' + 
                                    "var b = '\\n';" + 
                                    "var h = '';" + 
                                    "for (var i in cronometror.instancias[" + indice + "]) " + 
                                        "h += i + ': ' + b + String(cronometror.instancias[" + indice + "][i]) + b + b;" + 
                                    "alert(h);" + 
                                '"' + 
                        '>' + 
                            'configurações' + 
                        '</a>' +
                    '</div>' +
                '</div>';
            document.getElementById('painel_cronometros').appendChild(elemento);
            var parametros = 
                {
                    segundos: parseInt(document.getElementById('c1').value, 10),
                    alertar_faltando_segundos: parseInt(document.getElementById('c2').value, 10),
                    regressivo: document.getElementById('c3').checked,
                    iniciar: document.getElementById('c4').checked,
                    ao_terminar: new Function('i', document.getElementById('c5').value),
                    elemento: document.getElementById('cronometro_' + indice),
                    funcao_para_mostrar: null
                };
            if (document.getElementById('c6').checked)                             
            {
                parametros.funcao_para_mostrar = cronometror.mostrarPadrao;
            }
            if (document.getElementById('c7').checked)
            {
                parametros.funcao_para_mostrar = cronometror.mostrarAmigavel;
            }
            if (document.getElementById('c8').checked)
            {
                parametros.funcao_para_mostrar = new Function(document.getElementById('c9').value);
            }
            cronometror.criar(parametros);
            ++indice;
        }
    </script>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.