I have real time data coming in, based on which I have to change indicator in UI. Meaning if I don't receive data in the last 30 sec , the indicator should turn red. If data is received before thirty 30 sec, it should be green. Note that data comes into the function one after the other. The indicator should change for each data(curveName) in this case.
I have used $timeout and $interval, but unable to crack the problem. Any help will be appreciated.
You can maybe add in your controller something like:
var timer,
timeLimit = 30000; //30s limit
function onDataReceived(data) {
// cancel previous timer
if(timer) $timeout.cancel(timer);
// assuming data is good set indicator to green
$scope.indicator = "green";
// set 30s timer for indicator to go red
timer = $timeout(function(){
$scope.indicator = "red";
}, timeLimit);
}
Depending on how the data is received and your application structure, you can consider using something like:
$scope.$watch('data', onDataReceived);
Related
Currently, I have a problem like this:
I add a new user to a table "users" with status set to "new". Then after 5 - 15 minutes the status is changed to "Em". It's dependent on how large the data is.
I would like to make a wait time in mySQL to get the status "Em".
how can I make a wait condition until it changes status, maybe in 5 minutes it has changed status already. how can I count those waits and get the status in every minute of waiting
You can guild me by Javascript it's okay.
Thank you so much
I am not entirely clear what your request is. But here I can provide you with some insight. If we need to trace the elapsed time since the creation of a new user and calculate how long it still needs for the new user to reach the em status, we can use a view. And if we want MySQL to update the status automatically when the time is right, we can use an event scheduler to check periodically.
-- Here is the view supposing it takes 600 seconds to reach em since creation
drop view if exists testview;
create view testview as select user_id,user_status,
concat(time_to_sec(now()) - time_to_sec(ts),' seconds have passed since adding the user.') as since_creation,
concat(time_to_sec(date_add(ts, interval + 600 second)) - time_to_sec(now()),' seconds more to reach em status.') as wait_time
from users
where user_status='new';
-- Here is the event scheduler which checks every 10 seconds
set global event_scheduler=on ;
delimiter //
drop event if exists periodic_check //
create event periodic_check on schedule every 10 second starts now() do
BEGIN
update users set user_status='em' where user_status='new'
and time_to_sec(date_add(ts, interval + 600 second)) - time_to_sec(now()) <=0;
END//
I am wondering how i can solve the following issue. I have a Record in the Firebase DB which i am monitoring. The App is a Sports Score So far so good.
When user loads the initial page i check if Game is Running or Stopped and so a few things.
below is a snipped of what i do
if(Clock.Status=='Running'){
......
}
else if(Clock.Status == 'Stopped'){
.......
}
So far so good when user hits the page for first time. But now i want to monitor if the ClockStatus changes
clockStatusRef = firebase.database().ref("games/"+gameId+"/Score/");
clockStatusRef.on("child_changed", function(snapshot) {
var Clock = snapshot.val();
var status = Clock.Status;
// clock stopped - second scenario
if(status=='Stopped'){
stopTimer();
}
else if(status == 'Running'){
// clock status running- third scenario
firebase.database().ref('/.info/serverTimeOffset')
.once('value')
.then(function stv(data) {
console.log('hi');
serverTime = (data.val() + Date.now())/1000;
var timeElapsed = serverTime - Clock.ClockStart;
var totalCounts = document.getElementById("total_counts");
if(Clock.Timer > timeElapsed){
initTimer(Math.floor(Clock.Timer- timeElapsed),60);
}
else{
var Current_Clock = document.getElementById("count");
Current_Clock.innerHTML = '00:00';
}
}, function (err) {
return err;
});
}
console.log("Clock status changed: "+status);
});
for some strange reason on a change of status it starts with the main if
if(Clock.Status=='Running')
So i am wondering what am i missing and what is the best way to fix this so the first if is only run on the initial load and all subsequent will use the if's which handle status change of clock.
Here is the Json for games/B8120ACD-DF51-A64A-A83E-556007522E80/Score/Clock
{
"ClockStart" : 1510535632,
"Period" : 1,
"Status" : "Stopped",
"Timer" : 900
}
You're listening one level higher in your JSON than your code expects.
Either change the code that gets the clock from the snapshot to:
var Clock = snapshot.val().Clock;
Or (better, because it requires less data transfer) listen one level lower in the tree:
clockStatusRef = firebase.database().ref("games/"+gameId+"/Score/Clock");
As there seem to be some limitation as far as what is triggered when multiple listeners looking for changes and data overlaps i changed my code. As my App does not have any heavy traffic so changes are not that often, i use one listener for changes and to address my issue i just went ahead and added the run once for the initial setup then run different code on updates. Would have been nice to control what listener gets the notification of change, also the child_changed seems to have its limitations as i got it to fire but was not able to tell which child actually changed.
I have this javascript code where the setInterval() is triggered every 2 sec to update the var kraken_btc_eur
However sometimes the variable retrieved from the API does not change. Therefore, to save some serveur processing I would like to avoid the setInterval action to be triggered .
Maybe what I am asking does not make sense, it is just a though for optimisation.
Thank you for your guidance.
var kraken_btc_eur_old = 0;
setInterval(function(){
$.get('https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR', function(data){
var kraken_btc_eur = data.result.XXBTZEUR.c[0]; //get the value of 1 bitcoin
//some logic to change the css if the value increased or decreased
if (kraken_btc_eur_old > kraken_btc_eur) {
$(".kraken_btc_eur").css('color', 'red').text(kraken_btc_eur);
} else {
$(".kraken_btc_eur").css('color', 'green').text(kraken_btc_eur);
}
kraken_btc_eur_old = kraken_btc_eur; //set the global variable to the value of 1 bitcoin so that in 2 sec it will be checked in the if statement
$(".kraken_btc_eur").text(kraken_btc_eur); //show the value to the user to the html tag with the corresponding class
});
}, 2000);
With setInterval, you are using an approach called short-polling. This is when you continuously request data from the server to determine if anything changed.
There are two major alternatives to short-polling. Of these, I believe you are looking for WebSockets, which are essentially Sockets that you can use with JavaScript. WebSockets allow you to pass unformatted data from the client to the server, and vice versa. Using WebSockets, your server would have to keep an open socket to the client, but would only send data to the client if something changed on the server's side.
Of course, this is assuming you are the developer of the API.
If not, you'll have to stick to short polling. You could have an approach where if the value from the API doesn't change for a while, you could decrease the frequency of your short polls - but that would require you to switch from setInterval to setTimeout. In your callback, you could determine what the new timeout will be between the current callback and the next callback.
This approach would look something like the following:
setTimeout(function callback(timeout){
// .. get request here
if(timeout !== undefined)
{
if(kraken_btc_eur == kraken_btc_eur_old)
{
timeout = Math.min(10000, timeout + 1000);
}
else
{
timeout = 2000;
}
}
else
{
timeout = 2000;
}
setTimeout(callback.bind(window, timeout), timeout);
}, 2000);
I believe kraken api has an etag header not so sure. You can check if the etag is the same with the old etag means the data hasn't change.
Some reference.
http://www.websiteoptimization.com/speed/tweak/etags-revisited/
https://www.infoq.com/articles/etags
If you have the option of setting up a websocket its better. Check https://socket.io/.
You can make few changes in your code
var window.kraken_btc_eur_old = 0;
function makeRequest(oldValue) {
$.get('https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR',
function(data){
var kraken_btc_eur = data.result.XXBTZEUR.c[0];
if(kraken_btc_eur !== oldValue){
//get the value of 1 bitcoin
//some logic to change the css if the value increased or decreased
if (oldValue > kraken_btc_eur) {
$(".kraken_btc_eur").css('color', 'red').text(kraken_btc_eur);
} else {
$(".kraken_btc_eur").css('color', 'green').text(kraken_btc_eur);
}
window.kraken_btc_eur_old = kraken_btc_eur;
//set the global variable to the value of 1 bitcoin so that in 2 sec it will be checked in the if statement
$(".kraken_btc_eur").text(kraken_btc_eur); //show the value to the user to the html tag with the corresponding class
}
});
}
setInterval(makeRequest.bind(null,window.kraken_btc_eur_old), 2000);
I have written window.kraken_btc_eur_old just to give you an understanding that it's a global object
I’m making a html & Javascript game and I’m currently trying to write some code that will show the player’s gold balance on the screen and make it decrement by 1 every time the player clicks on a Javascript object (this object is placed in a div on the html page).
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a <div> but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
I don’t want the figure to decrement below 0. Instead, whenever it reaches 0 I want to initiate a Javascript modal to inform the player that they’ve run out of coins.
~~
Originally I was trying to use websockets to display the player’s balance on screen, but I found it very confusing (I’m a beginner at programming in general), so I’m now trying to load the balance on page load, then post the updated balance amount back to my database using AJAX every 60 seconds, or whenever the user closes the browser window, refreshes the page or navigates away from the page. I don’t know if it’s possible to do all these things, or where to start, maybe this is a really bad way to go about this and maybe it's not scalable (maybe the database wouldn't support constant updates from 1000s of players by using this method)?
I would really appreciate any advice or help anyone could give me on any of this.
Thanks in advance!
I’m going to grab the balance from my database using AJAX on page load, and then place it inside a but I have no idea how to make this figure decrement by 1 every time the Javascript object is clicked.
Here are two divs: you store the total number of coins in one and you click the second one to lose coins
<div id="coins">10</div>
<div onCLick="javascript:loseCoin()">If you click here it will cost you 1 coin</div>
Using a function to decrement the cost.
function loseCoin(){
var coins = getElementByid("coins");
var coins_nr = parseInt(coins.innerHTML,10);
if( coins_nr> 0 ){
coins.innerHTML = coins_nr - 1;
} else {
showModal();
}
}
Where showModal() will be your modal (ask if you don't know how to make it)
As for updating the database every 60 sec, you would need a timer loop such as:
setInterval(function () {
// get number of coins from your div's innerHTML
// then call your ajax controller to update DB
}, 60000);
An example of ajax using javascript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE ) {
if(xhr.status == 200){
console.log(xhr.responseText);
} else {
console.log('something else other than 200 was returned');
}
}
}
xhr.open("POST", "url_of_your_controller_here", true);
xhr.send("coins="+ coins_nr);
(maybe the database wouldn't support constant updates from 1000s of
players by using this method)?
Any decent server should have no problem handling 1000 requests every 60 sec, but it may depend on how many other requests it has and the complexity of your requests.
If you are just trying to decrement a visible counter in the window on each click, you can do something like this:
HTML:
<div id="coinsRemaining">20</div>
code:
// use whatever click handler is appropriate to your app
document.addEventListener("click", function(e) {
var elem = document.getElementById("coinsRemaining");
// get current display text and convert to number
var cnt = +elem.textContent;
--cnt;
if (cnt >= 0) {
elem.textContent = cnt;
}
if (cnt <= 0) {
alert("There are no more coins");
}
});
Working demo: http://jsfiddle.net/jfriend00/s9jb6uhf/
It seems like you don't need to update the database on every click unless there's some realtime aspect of your coin balance that affects other users. If you're just keeping track of your coin balance for future web page visits, then you could update the database much less often than every click.
i am working on a codeigniter project in which i am making a counter of every movie that is being clicked. Now i want if the user clicks the movie link the user is directed to the movie page and after 30 seconds the counter will be increased to 1. Currently the counter is increased on every click. Any Help???
Here is my view code
Watch in HD
Here is my controller code
public function watch_movie()
{
//$id = $_REQUEST['id'];
$id = $this->input->get('id');
$this->movie_counter->add_counter($id);
//$data['comment'] = $this->site_upload->fetch_comments($id);
//redirect ('site/play_movie', $result);
$this->load->view('Play_movie', $result);
}
Create a Queue!
Every click you insert into the queue, and another job (cronjob) insert every minute (smallest interval) the data from the queue in the correct table.
counter will be increased even every refresh too in this scenario, whateva you are saying for 30 sec interval ( you can use ajax request with a 30 sec timeout) but this seems like a buggy code what if some one closes it before 30 sec (browser) and you don't get any increment....
if you want to setup unique (views) use browser/ip/time based (for generic setup you can make it advance) and every time you get the request of counter addition check your db if you have same ip/browser and less duration as you say(30 sec or 1 min) then don't add other wise add 1 to script.