setInterval的{j}替代

时间:2017-12-22 23:46:46

标签: javascript jquery html ajax

我知道这是重复的,但我找不到我需要的东西。我尝试做一个实时的mmorpg(参考:travian,部落战争,ikariam等),以获得一些经验,仍然有一些乐趣(我童年的梦想)。 用户拥有多个城市,他可以使用“选择表单”访问每个城市。 当用户更改选择表单时,ajax将转到数据库并返回“当前城市资源:木材,铁,石头”以及“当前生产”'每个人。一切顺利。当我更改选择表单时,ajax正在使用值类上的循环更新资源栏。我将每小时用当前值+产品更新我的数据库存表(每10秒钟就会浪费一次)。问题是我想每5-10秒运行一次脚本,这应该更新客户端资源库存,如下所示:“document.getElemByID(wood).html = current dbStocked wood < / strong>(//已使用ajax查询一次)+(wood_production / 3600(一分钟内//秒)*((current_minutes * 60)+(current_seconds)))“。一切正常,但是当我用select形式更改城市时,setInterval继续运行,现在在脚本逻辑中有2个 wood wood_prod 值,现在每个itineration toogle之间这2例。每5秒钟,代表木材值的div得到:一次最后选择的城市计算,一次当前城市计算。所以div内容每5秒钟一次(间隔时间)。编辑:setInterval绑定了一个开始的值,即使被另一个取代也不会丢弃它,所以它强制初始值并用当前的值每隔5秒将它们移出。 这是我的代码的一部分:

$(document).ready(
  function() {
    $("#setCitty").on("change", getstats);
  }
);


function getstats() {
  var city = $('#setCitty').val(); //the select form triggering the ajax
  var identifier = $('#identifier').val(); //don t mind it
  $.ajax({
      type: 'post',
      url: 'handle/php/cityStatsGet.php',
      dataType: "json",
      data: {
        city: city,
        identifier: identifier,
      },
      success: function(response) {
        console.log(response.citystats);
        console.log(response.production); //Added console log here...all seems ok, changing city is changing the content of  response.citystats and response.production ..
        clearInterval(interval);
        var v = 0;
        $(".values").each(function() { //i have a mess here, i will use vanilla for performanece later
          $(this).html(response.citystats[v]);
          v++;
        });
        incoming();
        setInterval(incoming, 5000);

        function incoming() {
          var d = new Date();
          var m = d.getMinutes();
          var s = d.getSeconds(); //response.citystats[19] is iron stock
          $('#ironInc').html(parseInt(parseInt(response.citystats[19]) + ((parseInt(response.production[2]) / 3600)) * ((+parseInt(m) * 60) + parseInt(s))));
        } //i parseint all because i have a headpain trying to figure out what is wrong just because js treats pure numbers as strings
      });

  }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="values" id="ironInc"></span>

所以...我的问题是......如果我能以某种方式重新启动setInterval的执行(因为当我回想起它的patern函数时没有重新启动)。 编辑:还有,我在PHP

$stmt = $conn->prepare("SELECT * FROM city_stats WHERE user = ? AND city = ? ");
$stmt->bind_param('ss', $username, $city);  
$stmt->execute();   
$result = $stmt->get_result();
$row = $result->fetch_assoc();
//here are some math to get final values eg.:$income = $row['foo']+$row['bar'];
$data = array();

$data['citystats'] = array(
$population,$workers,$houses,$happiness,$popularity,$filantropy,$terror,$tax,
$foodFactor,$innFactor,$religion,$crime,$crowding,$rats,$food,$meat,$fruits,
$chease,$bread,$kiron,$kstone,$kgold,$kwood
     ); //23 ELEMENTs I<23
$data['production'] = array(
    $goldincome,$pwood,$piron,$pstone
);
$stmt->free_result();
$stmt->close();
$conn->close();
        echo json_encode($data);

2 个答案:

答案 0 :(得分:2)

setInterval(..)返回计时器的id。更改城市时调用clearInterval(id)。

var id = setInterval(..);

改变城市时

clearInterval(id);

这将停止从之前选定的城市

定期刷新木材等

答案 1 :(得分:1)

您可以使用async功能并使用promises

&#13;
&#13;
function sleepPromise(ms)
{
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function sleep()
{
    while(true)
    {
        // do something
        await sleepPromise(2000);   // Sleep desired amount of miliseconds
        // break if needed
        console.log('I have awakend.');
    }
}

sleep();
&#13;
&#13;
&#13;

编辑:以下是执行MySQLi查询后返回JSON的有效PHP文件结构的示例:

<?php
    $con = mysqli_connect(...    //Your connection info

    // Your query
    $result = mysqli_query($con, "SELECT name, price FROM ...");

    // If there are results
    if(mysqli_num_rows($result) > 0)
    {
        $resultArray = array();

        // Go through them row by row
        while($row = mysqli_fetch_array($result))
        {
            // Make the associative array for each row
            $arr = array ('name'=>$row[0],'price'=>$row[1]);
            // Add the row to a list of rows
            array_push($resultArray,$arr);
        }
        // set headers for JSON and json_encode the result array
        header('Content-type: application/json');
        echo json_encode($resultArray);
    }
    else echo 'error'
?>

编辑2:以下是使用javascript编写的promises代码。看看这是否适合你:

$(document).ready(function()
{
    $("#setCitty").on("change", getstats); 
};

// Returns promise
function goToSleep(miliseconds)
{
    return new Promise(resolve => setTimeout(resolve, miliseconds));
}

// Your tasks
function incoming(response)
{
    var d = new Date();
    var m = d.getMinutes();
    var s = d.getSeconds();
    $('#ironInc').html(parseInt(parseInt(response.citystats[19])+((parseInt(response.production[2])/3600))*((+parseInt(m)*60)+parseInt(s))));
}

// function to handle events
async function handleEvents(city, response)
{
    while(city == $("#setCitty option:selected").val())
    {
        incoming(city, response);  // call function to do stuff
        await goToSleep(1000*5);         // 5 seconds
    }
}


function getstats()
{
    var city = $("#setCitty option:selected").val(); // current selected item
    var identifier = $('#identifier').val();
    $.ajax(
    {
        type: 'post',
        url: 'handle/php/cityStatsGet.php',
        dataType: "json",
        data: {
        city: city,
        identifier: identifier,
    },
    success: function (response)
    {
        handleEvents(city, response);
    });
}