Once callable function in Javascript - javascript

I am developing a quiz component in Javascript and I have a startTimer() function in it which starts a countdown based on the value passed to it.
The function is called when the page loads and the quiz starts.
I don't what users to call the function again and alter the quiz time.
Is it possible to detect that the function is called a second time???

Any user can just disable JavaScript in their browser.
I would suggest that you record the time between the page being served and the answers coming back on the server and use that as the definitive source for how long they took. Perhaps allow a little buffer to compensate for network latency and page rendering time.
The JavaScript timer can be a nice UI feature to help the user know how much time they have left, but never trust a user interface, for a smart user will write his own UI (or in this case, configure the UI to not use JavaScript).

If you want to prevent people from changing any aspect of the quiz, you will have to implement the restrictions on the server.
It will be very hard, if not impossible, to prevent meddling with the quiz data on the client side.

Thanks everyone, I found this on net:
function createChance(){
var chanceLeft = true;
return function(){
if(chanceLeft){
console.log("This was the only chance you had.");
chanceLeft = false;
}
else{
console.log('Sorry: you already used your chance');
}
};
}
var chance = createChance();
chance();
// This was the only chance you had.
chance();
// Sorry: you already used your chance
any hacks for this????

Related

Storing a variable to web server

I have a page on my site where you can play a game. When you die in the game, a function called "playerIsDead();" is called, then the game closes (The game screens are prompt();s and confirm();s shown one after another, so by "the game closes", I mean the page stops showing popup messages.). The playerIsDead(); Function:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
};
I want to make the function increase a variable, totalDeathCount, by one each time, like this:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
totalDeathCount++;
};
So, my question is, how can I store totalDeathCount to the server, so I can display it on the page? I don't want it to show how many deaths have happened locally, I want it to show how many worldwide deaths have occurred.
Any help would be much appreciated!
You could use a MySQL database and store the value using PHP. Or you could simply use javascript's localStorage to store them locally on the device.
var newDeathCount = localStorage.getItem('totalDeathCount') + 1;
localStorage.setItem('totalDeathCount',newDeathCount);
Then you basically stored how many times they have died. Not in a web server but this is an alternate solution.
1) Decide how and create something to persist the information. E.g. write it to a file, store it in a database, etc.
2) Write a simple php script to store the data. (or implement it as part of your existing php backend if available)
3) Make an ajax post request to send the data to the script.
For implementation details use google and your imagination. ;)

display number of message dynamically using javascript or asp.net

I will do my best to explain my problem to avoid people pointing me into different directions.
I got an assignment from business people. I don't know the terminology. It is very similar to email notification, message notification on facebook, notification on social media games.
For example, people are sending 20 email messages 5 minutes ago. the screen will display 20 (see attachment). Now, 3 more messages have arrived, the web page should update the number to 23.
Facebook has similar concepts when our friends like/comment message. The notification changes. Same thing is true on social media game. Any status changes on our game, it will reflect it.
I kind of have idea on how to do it cosmetically (on CSS). How to do it using javascript/asp.net. Do I need to postback in order to refresh the message. I never pay attention to that on facebook/yahoo email/social media games. All I know is something is happening, the webpage is updating the status.
Sorry the question is too broad. If someone can help me to point to the right direction, I appreciate any help
HTML5 introduced a very interesting concept call Server-Sent Events in which server can dynamically connect to the client and send data.
Eg:
var source = new EventSource("demo_sse.asp");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data + "<br>";
};
And on server side you can write,
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
<!--Writing "data:" is important-->
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
However, some old browsers may not support this.
One other way to accomplish this task is to use Ajax call as,
function checkNewMessages(totalMessages){
return $.ajax({
url: 'demo.asp',
type: 'GET',
cache: false,
data: {
totalMessages: totalMessage;
}
});
}
checkNewMessages(totalMessages).success(function (data) {
// display the data wherever you want
});
//Checking for new messages every 5 seconds
setInterval(checkNewMessages(totalMessages,5000));
Whatever you write within your Write() in server side will be displayed here. Now to constantly check for the new messages you can call the above ajax function with the help of setInterval()
There are many ways to do this, depending on how real time you need it to be.
The most common way is to use JavaScript with an XmlHttpRequest to call an ASP.NET page which returns the number of messages, I recommend you use a JSON object for this. The benefit of this approach allows you to request data from the server without the user experiencing a full page refresh. You can use JavaScript to set it to call every x seconds depending on your requirements.
Collectively that is known as AJAX, using a JavaScript library such as JQuery can make this much easier.

Creating user turn based game in Javascript

I've created a whiteboard web app where a multitude of registered users, login and start drawing on the html5 canvas. I devised the 'multiplayer' aspect of the game through python websockets and the login is made with php, currently the canvas page has a 'session_start();' so I can be able to add a feature to see who's currently using the application and I feel it may come in hand for the 'turn based' aspect as well.
Now I'm trying to prevent users from being able to draw on the canvas at the same time, if possible i'd like every user to have a fair turn at drawing on the canvas. I'm not sure how I'd accomplish this but I feel that Javascript will most definitely be the logic behind this.
Any advise or suggestions as to how I'd go about achieving this feature?
EDIT
Ok since nobody has any answers or suggestion I'll try and provide to you what I've attempted so far, I think it may be on the right direction even though it doesn't work:
var player = document.getElementById("inputnameid").value;
var currentPlayer = player; // player class
//array of player objs.
var array1 = [player]; // list that OnCurrentPlayerEndTurn cycles through to choose user
// call this at the start of the app
function OnStartTurn()
{
currentPlayer.OnBeginTurn();
var inputs=document.getElementById('inputty');
for(i=0;i<inputs.length;i++){
inputs[i].disabled=false;
}
//This function will activate the GUI so the user can now act
}
// call this function when setTimeout is 10 seconds
function OnCurrentPlayerEndTurn()
{
setTimeout('OnCurrentPlayerEndTurn();', 10*1000);
change currentPlayer variable to the next player in line
OnStartTurn(); // will cause the next player to begin his turn
}
Your question seems to be focused on the front-end code, which, while important, is not the critical part of this problem. As you've noted, the core of a turn-based game is the round-robin passing of active players. You probably want this to be done server-side: it's much easier to coordinate the various players from there.
You'll maintain a list of the players in a given game on the server. Before the game starts each client will register with the server and an identifying user id is stored there. Then in each round, the server allows each player a turn. The turn order is of course up to the specifics of the game, but the general idea is the same whether turn order is fixed or fluid.
As each player's turn comes around, the server sends a ticket to that player's client. This is essentially a one-time pad (OTP) concept: generate a random token that is hard to guess (so don't use just an increasing integer, but instead some cheap hash function or the like). The client then sends this ticket along with the request for the move they would like to make, and the server validates that the ticket corresponds to the currently active player before taking any action.
Depending on the rules and requirements of the game, the server can then immediately invalidate the ticket (e.g., chess), can wait until an 'end of turn' move, or can invalidate the ticket after some amount of time. The server then generates a new ticket for the next player to go.
The client-side code follows naturally from this architecture. All inputs can be disabled by default, and only enabled when the client holds a valid ticket. If the ticket is designed to time out, you probably want a method of querying the server to determine if it is still valid. If the user is always responsible for ending their own turn (explicitly or implicitly) you can get away without that.

What is the best way to implement idle time out for web application (auto log off)

I want to implement an idle time-out for the web application that we are building. I had earlier achieved this using AsynchronousSessionAuditor from codeplex, which essentially looks for the formsauthentication and session cookie timeout by constant polling.
But it has a draw back of not respecting the client side events, it will look for only last postback to decide when to log off.
The jquery plug jquery-idle-timeout-plugin from erichynds solves this issue of client side events but suffers from another drawback that is not able to recognise user is active on some other tab.
Is there anyone already fixed the TABBED browsing issue with jquery-idle-timeout-plugin already? Or is there any better approach of application time out for web applications (by the way this web app is build using asp.net f/w)
If I understand your question right, it is not possible, since there are no events triggered in javascript for activity outside of the current window/tab.
Unless you have a addon to go along with your website for each browser, which could monitor all activity in the browser, but that is not really a practical approach.
Well, you'd have to code it by hand, which is not really hard. You can use the onfocus and onblur functions to do something like this:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (!window.isActive) { /* Check for idle time */}
}
If you make a little search you can find that varaieties of this question have already been asked and answered, you can probably find a solution you can implement with one of the plugins you mentioned.
Try:
Run setTimeout only when tab is active
or
How to tell if browser/tab is active
EDIT--> ADDED:
Or I'd try a different approach. You could create a cookie with some hash and save that hash in your DB with a timestamp that updates whenever the window is active (you could check every 5 seconds or something, it's not an intensive request)
Then, do another check before(but in the same request) to see how much time has passed since the last timestamp and log them out if necessary.
it won't log them out isntantly when time has passed, but it will when they try to access the site either by opening it again or by focusing on the tab/window.

Is there a way to set a Web Worker to low priority?

I am thinking of using Web Workers to provide some background functionality while a user is browsing my website (that's what Web Workers are for, right?). However, I don't want to take the risk of compromising the user experience by causing laggy scrolling, unresponsive controls, etc. Web Workers are mapped on OS threads, hence I would expect some control on the priority of these threads however, as far as I know, there's no such thing in the current API. Do you know a how to accomplish this? Even with a hack?
Well, there's no API call to control low-level details like this. However, I think you should first implement what you want to do and then test if the performance hit is too great on the user experience. I'm assuming that since they did not add fine control over how the threads execute, they're probably well managed by the underlying implementation.
Even with a hack? [...]
the user uploads a photograph and the worker applies a Photoshop-like
filter to it, which is pretty CPU intensive, then the worker alerts
the main thread
Here's a hack.
Slow down your code. Something like this is what I am currently using for a particle simulation:
var TIME_STEP = 10,
paused = false,
state; // set by commands.start()
function main_loop () {
if (paused) {
return;
}
// update state incrementally. Break your process into chunks
// for example pixels or rows of pixels
state = ____________;
// send state or progress to main thread
if (finished) {
self.postMessage(state);
} else {
self.postMessage(progress);
}
setTimeout(main_loop, TIME_STEP);
}
var commands = {
//...functions that can be called from main thread (pause/start/cancel/etc)...
};
function message_handler (event) {
var data = event.data;
var command = commands[data.command];
command.apply(this, data.args);
}
self.addEventListener('message', message_handler, false);
TIME_STEP is the time between calculations and will need to be different depending what you are doing and how long you can afford to increase it's time. One good thing about doing it this way is that you can accept pause and cancel requests between iterations.

Categories

Resources