Ir ao conteúdo
  • Cadastre-se

somar valores em javascript


Posts recomendados

boa

gostaria de saber como se cria em javascript um somador  que esta constantemente a somar

segue-se o código como no ogame na parte de recursos

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="Game">
    <meta name="author" content="Pedro Alves">
    <link rel="icon" href="../favicon.ico">

    <title>Game</title>

    <!-- Bootstrap core CSS -->
    <link href="dist/css/bootstrap.min.css" rel="stylesheet">
<link href="dist/css/menu.css" rel="stylesheet" type="text/css">
<link href="dist/css/styleimage.css" rel="stylesheet">
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <link href="dist/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="dist/css/starter-template.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="dist/js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
 <script type="text/javascript">
 function startTime() {
     var today=new Date();
     var h=today.getHours();
     var m=today.getMinutes();
     var s=today.getSeconds();
     // add a zero in front of numbers<10
     m=checkTime(m);
     s=checkTime(s);
     document.getElementById('txt').innerHTML=h+":"+m+":"+s;
     t=setTimeout('startTime()',500);
 }

 function checkTime(i){
 if (i<10) {
     i="0" + i;
 }
     return i;
 }
 </script>
  </head>
<body  onload="startTime()">


<?php 
require_once('../configurations/auth.php');
require_once('../configurations/Database.php');

$ola=$_SESSION['SESS_LOGIN'];	 
include ('include/menu.php');?>
<div id="conteudo-left"> 
<h1> <img src="../imagens/logo.ico">Game </h1> 
</div>
<div id="conteudo-right">
  <h5>
<img width="25px" height="25px" src="../imagens/recursos/ouro.png">500 
  	<img width="25px" height="25px" src="../imagens/recursos/madeira.png">500
    <img width="25px" height="25px" src="../imagens/recursos/metal.png">500 
    <img width="25px" height="25px" src="../imagens/recursos/pedra.png">500
    <img src="../imagens/logo.ico">500 energia
    <img src="../imagens/logo.ico">500 comida
    <img width="25px" height="25px" src="../imagens/recursos/petrolio.png">500
     <img src="../imagens/logo.ico">500 dinheiro  
  
  	
    </h5>
   </div>
   
 <div style="width:100%;height:50px;background-color:#FFF"></div>
 
 

<div class="container-fluid"  style="background-color:#FFF;height:550px;">
  
  <div class="row" style="width:100%">
    <div class="col-sm-4" style="width:25%">
	<?php include ('include/vermenu.php');
 ?>
 </div>
    <div class="col-sm-4" style="background-color:#FFF; width:50%">
    <div style="height:50px;background-color:#000;"> Mensagens  
    </div>
    <div style="background-color:#0F9;height:700px"> fdssdklfsdklfjskldfjkldsjfl</div>
     </div>
    <div class="col-sm-4" style="background-color:#000; width:25%;height:100%" >cidades </div>
  </div>
 
   
  </div>

                 
<div>
            
  <?php  
include ('include/footer.php');
?>
</div>



    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="dist/js/jquery.min.js"><\/script>')</script>
    <script src="dist/js/bootstrap.min.js"></script>
    <!-- Just to make our placeholder images work. Don't actually copy the next line! -->
    <script src="dist/js/holder.min.js"></script>
   
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="dist/js/ie10-viewport-bug-workaround.js"></script>
    
      <script src="dist/js/bootstrapValidator.js"></script>
   <script src="dist/js/bootstrapValidator.min.js"></script>
   
  </body>
</html>

 

Link para o comentário
Compartilhar em outros sites

  • Moderador

@Landi20 Você se refere as horas minutos e segundos em tempo corrido?

 

Se for isso, está errado a linha que diz setTimeOut.

Deve-se usar setInterval.  

 

Assim:

 

setInterval(function(){ 
 	startTime();
 }, 
 500);

O código completo fica:

function startTime() {
     var today=new Date();
     var h=today.getHours();
     var m=today.getMinutes();
     var s=today.getSeconds();
     
     // add a zero in front of numbers<10
     m=checkTime(m);
     s=checkTime(s);
     document.getElementById('txt').innerHTML=h+":"+m+":"+s;
     
 }

 function checkTime(i){
 if (i<10) {
     i= "0" + i;
 }
     return i;
 }
 
 setInterval(function(){ 
 	startTime();
 }, 
 500);

Repare que foi retirado o setTimeout de dentro da função e lá em baixo é chamado o setInterval()

Veja funcionando: https://jsfiddle.net/dife/vdLjy758/

 

Você poderia fazer isso com jQuery.. já que você está usando ele com o bootstrap.

O código iria ser reduzido e fica mais elegante

Link para o comentário
Compartilhar em outros sites

  • 3 semanas depois...

não estou a conseguir por código a funcionar

o resultado devia ser

125

150

175

e esta me dar sempre 125

segue-se o codigo

servidor.php

<?php

require_once ('configurations/config.php');

// arquivo cujo conteúdo será enviado ao cliente

//$dataFileName = 'data.txt';


$timestart=time();
$PDO = new PDO('mysql:host=localhost;dbname=game', 'root','');

if(isset($_POST ['timestamp'])){

    $timestamp=$_POST [ 'timestamp' ];

}
else {
    $tempo=$PDO->prepare("SELECT NOW() as now");
    $tempo->execute();
    $row=$tempo->fetchObject();
    $timestamp=$row->now;
}
/* $sql = $PDO->prepare( "SELECT * FROM comments WHERE timestamp >'$timestamp'" );

 $newdata = false;
 $notificacoes=array();
 while (!$newdata &&(time()-$timestart)<20) {
     $sql->execute();
 while ($row=$sql->fetchAll(PDO::FETCH_ASSOC)) {

     $notificacoes=$row;
        $newdata=true;
 }  
 usleep(500000);  
 } 
 $tempo=$PDO->prepare("SELECT NOW() as now");
    $tempo->execute();
    $row=$tempo->fetchObject();
    $timestamp=$row->now;
    $data= array('notificacoes'=>$notificacoes,'timestamp'=>$timestamp);
    echo json_encode($data);
    exit();

*/
$sql = $PDO->prepare("SELECT cidade.ouro,cidade.madeira,cidade.metal,cidade.pedra,cidade.energia, cidade.comida,cidade.petrolio FROM users INNER JOIN cidade ON users.cod_user=cidade.cod_user WHERE cidade.timestamp>'$timestamp'AND users.username='admin';");

 $newdata = false;
 $notificacoes=array();
 while (!$newdata &&(time()-$timestart)<20) {
     $sql->execute();
 while ($row=$sql->fetchAll(PDO::FETCH_ASSOC)) {

     $notificacoes=$row;
        $newdata=true;
 }  
 usleep(500000);  
 } 
 $tempo=$PDO->prepare("SELECT NOW() as now");
    $tempo->execute();
    $row=$tempo->fetchObject();
    $timestamp=$row->now;
    $data= array('notificacoes'=>$notificacoes,'timestamp'=>$timestamp);
    echo json_encode($data);
    exit();
?>

client.js

$(function(){
notificacoes();
});
function notificacoes(timestamp){
    var data={};
    var resultado=0;
            var soma=2;
            var valor=25;
    if(typeof timestamp!='undefined')
    data.timestamp=timestamp;
    $.post('server.php',data,function(res){
        for(i in res.notificacoes ){

            resultado=+res.notificacoes[i].ouro+valor;

            $('#response').append(resultado);
        }

        notificacoes(res.timestamp);
    },'json');

}

ola.php

<html>

	<head>

		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

		<script type="text/javascript" src="dist/js/client.js"></script>

	</head>

	<body>

		<h3>Conteúdo</h3>

		<div id="response" name="response"></div>

	
	</body>

</html>

alguém me pode ajudar

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...