setInterval running more times than intended? - javascript

I have an application written in node.js using socket.io. The main event loop looks like this:
io.on("connect", function(CLIENT) {
//Run this code when a client connects
SERVER.connectPlayer(CLIENT);
//Recieve input from client
SERVER.handleInput(CLIENT);
//Run this code when a client disconnects
CLIENT.on("disconnect", function() {
SERVER.disconnectPlayer(CLIENT);
});
});
function main() {
SERVER.update();
}
setInterval(main, SERVER.tickRate);
This works fine, but I'm having an issue with SERVER.handleInput:
//Recieve input from the client
Server.prototype.handleInput = function(client) {
client.on("sendKey", function(data) {
client.player.handleKey(data.key, data.pressed);
});
client.on("sendMouse", function(data) {
client.player.mouse_x = data.x;
client.player.mouse_y = data.y;
});
}
Both of these work fine, but the second method client.on("sendMouse") triggers my main() loop above whenever it is run. I've tried commenting out the body of sendMouse but that doesn't change anything.
This method is being triggered by the client whenever the user moves the mouse. This is the code I'm using:
//Handles input on the client and sends it to the server
Game.prototype.bindKeys = function() {
var game = this;
this.input = {};
document.addEventListener("mousemove", function(event) {
game.mouseMove(event);
}, false);
}
Game.prototype.mouseMove = function(event) {
this.setMousePos(event);
client.emit("sendMouse", this.mouse);
}
setMousePos just figures out the current position of the cursor and sets it so that the client knows what coordinates to send back to the server. If I remove sendMouse on the client the game runs perfectly but otherwise my main setInterval loop is being run additionally every time sendMouse triggers.
I have no idea what would cause this. The keyboard input works perfectly fine. I'd greatly appreciate any advice.

Related

Microsoft Azure Text to Speech - Stop Recording On Button Press - StopRecognitionOnceAsync() Not Working?

Apologies in advance for any terminology mistakes, I'm a student and trying my hardest to be as clear as possible! and thanks in advance for any help!
I'm trying to use Azure Speech-To-Text services. I'd like the user to be able to press a start and stop button to record themselves and print out the transcription. My app will eventually be a React Frontend and Rails backend, but right now I am just trying to understand and work through the demo.
I'm confused by the documentation but was able to get things half working. However, right now it just continuously listens to the speaker and never stops.
I want to use stopContinuousRecognitionAsync() or recognizer.close() once a button is pressed, but I cannot seem to get it working. The farthest I've gotten is the result is logged only once the stop button is pressed, but it continues to listen and print out results. I've also tried using recognizer.close() -> recognizer = undefined but to no avail. I am guessing that due to the asynchronous behavior, it closes out the recognizer before logging a result.
The latest code I've tried is below. This result starts listening on start click and prints speech on stop, but continues to listen and log results.
// subscription key and region for speech services.
var subscriptionKey, serviceRegion;
var authorizationToken;
var SpeechSDK;
var recognizer;
document.addEventListener("DOMContentLoaded", function () {
startRecognizeOnceAsyncButton = document.getElementById("startRecognizeOnceAsyncButton");
subscriptionKey = document.getElementById("subscriptionKey");
serviceRegion = document.getElementById("serviceRegion");
phraseDiv = document.getElementById("phraseDiv");
startRecognizeOnceAsyncButton.addEventListener("click", function () {
startRecognizeOnceAsyncButton.disabled = true;
phraseDiv.innerHTML = "";
// if we got an authorization token, use the token. Otherwise use the provided subscription key
var speechConfig;
if (authorizationToken) {
speechConfig = SpeechSDK.SpeechConfig.fromAuthorizationToken(authorizationToken, serviceRegion.value);
} else {
speechConfig = SpeechSDK.SpeechConfig.fromSubscription(“API_KEY”, serviceRegion.value);
}
speechConfig.speechRecognitionLanguage = "en-US";
var audioConfig = SpeechSDK.AudioConfig.fromDefaultMicrophoneInput();
recognizer = new SpeechSDK.SpeechRecognizer(speechConfig, audioConfig);
recognizer.startContinuousRecognitionAsync(function () {}, function (err) {
console.trace("err - " + err);});
stopButton = document.querySelector(".stopButton")
stopButton.addEventListener("click", () =>{
console.log("clicked")
recognizer.recognized = function(s,e) {
console.log("recognized text", e.result.text)
}
})
});
Assuming the recognizer is conjured correctly outside of the code, there's a few things to change to get the result you want.
The events should be hooked to the recognizer before calling startContinuousRecognition().
In the stop button handler, call stop. I'd also hook the stop event outside of the start button click handler.
Quick typed changes, didn't compile. :-)
startRecognizeOnceAsyncButton.addEventListener("click", function () {
startRecognizeOnceAsyncButton.disabled = true;
//div where text is being shown
phraseDiv.innerHTML = "";
// The event recognized signals that a final recognition result is received.
recognizer.recognized = function(s,e) {
console.log("recognized text", e.result.text)
}
//start listening to speaker
recognizer.startContinuousRecognitionAsync(function () {}, function (err) {
console.trace("err - " + err);});
});
stopButton = document.querySelector(".stopButton")
stopButton.addEventListener("click", () =>{
console.log("clicked");
recognizer.stopContinuousRecongition();
};

Execute a function when a nodejs event is received

I might missing something basic, but here is my goal: I have a small instant chat example based on tutorial found here Instant Chat for drupal
The principle is to connect to a nodejs server that basically just broadcast all messages it receives.
I have this function on the client side (inside a drupal tpl.php file):
(function($) {
var myNick = 'me';
var socket = io.connect('http://<?php print $_SERVER['SERVER_ADDR'] ?>:8081');
socket.on('connect', function() {
$('#chat').addClass('connected');
});
socket.on('user message', message);
function message(from, msg) {
if (msg == 'GO') {
** EXECUTE A FUNCTION HERE **
} else { //display the message and sender
$('#lines').append($('<p>').append(from, msg));
}
}
$(document).ready(function() {
$('#send-message').submit(function() {
message(myNick, $('#messageinput').val());
socket.emit('user message', $('#messageinput').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
})(jQuery);
When I send a message with content =GO, the submit is executed, the message(..,..) function is called and my specific function is executed properly.
But when I receive a GO message, the socket.on event triggers, message() function is called, but my specific function is NOT executed.
Any Idea how I can fix this?
Many thanks for your help.
Michael.

jQuery | Is calling setTimeout on mousemove bad practice/inefficient?

This code determines if the user is online :
/* User online status */
var online = true;
var activeTimeout = setTimeout(_setUserInactive, 5000);
$(document).on("mousemove keydown keyup click", function () {
clearTimeout(activeTimeout);
activeTimeout = setTimeout(_setUserInactive, 5000);
if (!online) {
_setUserActive();
}
});
Pretty simple. But, is this going to cause performance issues? It will call every time the mouse is moved. Thanks.

How to start javascript setinterval once cleared?

I have a setinterval that runes every 5 seconds. this works fine on page load.
I have the following scenarios:
Load page with interval (WORKS)
press button and load new content and stopp interval(WORKS)
Once the new content is no longer desiered, dissmiss it, return to first content and start interval again(DOES NOT WORK)
I have saftys suchs as events for window.blur that also stops the interval so that the browser does not commponsate for all the missing intervals if i would change tabs or something. Keep in mind that step 3 did not work BUT if i would after step 3 change a tab and then return to my original page(execute blur) the interval would start working again.
NOTE all content loading here exept page load is done with ajax calls.
My code:
initializing:
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function() {
$.automation.tanks.tableInit();
});
binding function:
bindIntervalEvent: function (target, url, callback) {
$(window)
.on("focus.mine",
function() {
$.automation.worker.setUpdateInterval(target, url, callback);
})
.on("blur",
function() {
$.automation.worker.stopUpdateInterval();
}).trigger("focus.mine");
}
interval function:
setUpdateInterval: function (target, url, callback) {
if ($.automation.globals.globalInterval.value.length === 0) {
$.automation.globals.globalInterval.value.push(window.setInterval(
function () {
var options = {
loadTarget: target
}
$.automation.worker.getView(url,
function() {
if (callback)
callback();
},
options);
},
5000));
}
}
the function that stops the interval:
stopUpdateInterval: function () {
if ($.automation.globals.globalInterval.value.length === 0)
return;
console.log("deleting");
for (var i = 0; i <= $.automation.globals.globalInterval.value.length; i++) {
window.clearInterval($.automation.globals.globalInterval.value[i])
$.automation.globals.globalInterval.value.splice(i, 1);
console.log($.automation.globals.globalInterval.value.length);
}
}
when stopping the interval i also remove the window bindings:
unBindIntervalEvent: function() {
$(window).off("focus.mine");
$(window).unbind("blur");
}
Back to step 3:
My sucess method in the callback to my getviewfunction is identical to what i execute in the beginning
code:
$(".updatelatest")
.on("click",
function () {
var _this = $(this);
var options = {
loadTarget:"#TanksContent"
}
$.automation.worker.getView("/Tank/GetTanks",
function (data) {
$(_this).switchClass("col-md-5", "col-md-1", 1000, function() {
$(_this).addClass("hidden");
$(".search").switchClass("col-md-5", "col-md-12", 1000, "easeInOutQuad");
})
$.automation.tanks.tableInit();
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
$.automation.tanks.tableInit();
});
$(window).trigger("blur");
}, options);
});
but this does not start the interval. it is clearly initialized since it works when window.blur is executed for example when I change tab but for some reason this is not working beyond that.
i tried triggering the windows blur event and nothing happened, i tried triggering my custom window event "focuse.mine" but nothing happens.
I did not notice this while developing since I had firebug open and every time i checked scripts or css or the console the blur function was executed so I assumed that my code worked as intended but now that it is deployed I notice this.
My head is pounding beyond reason and I can't for figure out where I have gone wrong.
Well this was a fun one. I simply found that when calling the setUpdateInterval(); function directly it gave me the desiered result.
I realized that the reason I had them split like I did was becaouse of the blur event. "Focus.mine" is triggered to start the inteval again ocne a user comes back to the page.

Firefox OS alarm to wake up closed app

Looking at documentation it looks like the alarm api can be used to restart an app at a certain time
I changed the code from boilerplate example in this way
// Alarm API
var alarmDate = new Date("Jul 8, 2014 19:35:00"),
addAlarm = document.querySelector("#add-alarm"),
alarmDisplay = document.querySelector("#alarm-display");
if (addAlarm) {
addAlarm.onclick = function () {
var alarm = navigator.mozAlarms.add(alarmDate, "honorTimezone", {
"optionalData" : "I am data"
});
alarm.onsuccess = function () {
var request = window.navigator.mozApps.getSelf();
request.onsuccess = function() {
navigator.mozSetMessageHandler("alarm", function (mozAlarm) {
request.result.launch();
alert("alarm fired: " + JSON.stringify(mozAlarm.data));
});
};
request.onerror = function() {
alert("Error: " + request.error.name);
};
};
The code seems to bring up the app only if the app is running (even in background) BUT not if the app is closed.
Is this the intended behaviour? Any way to restart a closed app?
Also is it possible to bring up the app in foreground and make it unlock the screen?
Thanks
UPDATE
Just as a clarification, the issue appears when the system memory load requires killing an app. Android provides a way to schedule restart of an app (while iOS, afaik, does not...).
It would be useful if an app could be restarted at the moment in which it's required.
That's also saving a lot of battery...
Your code is wrong: the setMessageHandler is created in the onsuccess handler of mozAlarms.add. That code will not be executed when the alarm fires. You need to always add the listener on app startup.
Here's some simple code that adds and responds to an alarm (from app-days-dhaka).
var request = navigator.mozAlarms.add(new Date((+new Date()) + 30000), 'ignoreTimezone', {
type: 'yolo'
});
console.log('setting to', new Date((+new Date()) + 30000) + '')
request.onsuccess = function() {
console.log('success');
}
request.onerror = function() {
console.error('err');
}
navigator.mozSetMessageHandler('alarm', function() {
console.log('alarm');
launchSelf();
});
function launchSelf() {
var request = window.navigator.mozApps.getSelf();
request.onsuccess = function() {
if (request.result) {
request.result.launch();
}
};
}
Open the app (this will set the alarm), then close the app immediately (via long press on home). After 30 seconds the app will open again automatically.

Categories