php - JavaScript: How to set for setInterval function a custom behaviour -
i need set custom behaviour setinterval
js function;
this part of online game, , script used keep data updated;
worlds[world_id].building
traffic light, true
grren , false
red values, know;
i used following function obtain array;
this js
function:
function init() { $.ajax({ type: "post", url: '<?php echo yii::app()->baseurl; ?>/robots/default/loadworlds', data: {}, success: function(data) { if (data) { if (data.status === true) { if (data.worlds) { worlds = data.worlds; $.each(data.worlds, function(key, value) { addelement(key, value); count_world_ids++; }); } } } }, datatype: 'json', }); }
the js
function calls php
method:
public function actionloadworlds() { $worlds = array(); $status = true; $result = array( 'worlds' => &$worlds, 'status' => &$status, ); $model_worlds = worldm::model()->findallbyattributes(array('status' => worldm::active)); if ($model_worlds) { $ind = 0; foreach ($model_worlds $key => $model_world) { $ind++; $worlds[$ind] = array( 'id' => $model_world->id, 'battle' => true, 'building' => true, 'troop' => true, 'resources' => true, ); } } else { $status = false; } echo json_encode($result); exit; }
now have obtained array, can each
, ass seen in js
function , call addelement
js function;
within addelement
js function, after insert div
elements needed, call js functions:
setinterval(function() { fbattle(value['id']); }, 1000); setinterval(function() { fbuilding(value['id']); }, 1000); setinterval(function() { ftroop(value['id']); }, 1000); setinterval(function() { fvillageresources(value['id']); }, 1000);
so, each world, functions triggered, @ 1 second interval;
if have 10 worlds, fbattle(value['id']);
triggered 10 times;
now, comes issue:
why fbattle
triggers @ same time worlds?
it has different param, 1 ... n worlds;
also, within fbattle
function there traffic light, , if job not finished , should not trigger;
this process should async
, because on different worlds, job might not finished;
function fbattle(world_id) { if (worlds[world_id].battle == true) { worlds[world_id].battle = false; document.getelementbyid('battlepermission' + world_id).innertext = 'working'; $.ajax({ type: "post", url: '<?php echo yii::app()->baseurl; ?>/robots/battle/test', data: {}, success: function(data) { console.log('battle ' + world_id); console.log(data); worlds[world_id].battle = true; document.getelementbyid('battlepermission' + world_id).innertext = 'finished'; }, datatype: 'json', }); } }
for now, job each action:
public function actiontest() { $sleep = rand(1, 10); sleep($sleep); echo json_encode(array('result' => true, 'sleep' => $sleep)); exit; }
i know action triggered in same time worlds, , rand
value same same js
function;
Comments
Post a Comment