Background: the code below picks either a word or an image and displays it in my 'abc' div. It measures the reaction time.
Aim: I want to have the function run only 8 times (not 8 keypresses), record the time for each run regardless the keypress event (i.e. a time of 2000 when no key is pressed), and I want this function run first, and after it has finished I want to run a second function.
I researched the $deferred method and seem to have failed to adopt it. Furthermore, my 8 function runs, are not eight at all, but seem more like 8 simultaneous runs.
So basically I want to run my function 8 times, then run a next function, and record the time from appearance of a stimulus to the next if not interrupted by keypress.
I'm stuck with it for some time now and have probably lost the overview.
var reac_arr = [];
var t1;
function firstFunction(){
var def = $.Deferred();
for (var i = 1; i <= 8; i++) {
$(function cit(){
var timeout = 0;
function showNext(){
t1 = (new Date()).getTime();
if (Math.random() < 0.5) {
var new_word = stim.name;
$("#abc").text(new_word);
}
else {
var new_img = stim.path;
$("#abc").empty();
var prox_img = $('<img id="abcimg">');
prox_img.attr('src', new_img);
prox_img.appendTo('#abc');
}
timeout = setTimeout(function(){
showNext()
}, 2000);
}
$(document).keypress(function(e){
if ($(e.target).is('input, textarea')) {
return;
};
clearTimeout(timeout);
if (e.which === 97 || e.which === 108 || e.which === 32) {
setTimeout(function(){
showNext();
}, 300);
var t2 = (new Date()).getTime();
var reac_time = t2 - t1;
reac_arr.push(reac_time);
}
});
});
};
setTimeout(function() {
def.resolve();
}, 1000);
return def.promise();
}
function secondFunction(){
var def = $.Deferred();
alert("It works!")
};
setTimeout(function() {
def.resolve();
}, 1000);
return def.promise();
}
firstFunction().pipe(secondFunction);
Your code seems a bit bloated but if I understood correctly all you need is setInterval().
var counter = 0;
var ticker = setInterval(myFunction,2000);//Setup a function to run every 2000ms
function myFunction()
{
//do your thing
counter++;//
if(counter==8){
//on the 8th time run next function...
}
}
$(document).keypress(function(e){
clearInterval(ticker);//Stop the ticker on keypress
});
Related
I run a script in the browser that scrolls the page down. I run it from the browser console (ctrl + shift + j).
var popWys = 0;
var terazWys = 0;
var proba = 0;
function scrollowanie() {
if(popWys == document.body.scrollHeight)
{
proba++;
if(proba > 10)
{
window.alert("To juz chyba wszystko, w razie czego odpal ponownie.");
return;
}
}
else
{
proba = 0;
}
popWys = document.body.scrollTop;
terazWys += 1000;
window.scrollTo(0,terazWys);
setTimeout(scrollowanie, 100);
}
setTimeout(scrollowanie, 100);
Question. How to stop it at any time from the command line? Can I write something, press to stop? Sam will never stop and blocks the browser. I tried with different: return; break; Stop. anything and nothing works.
Can it be done at all?
You can use clearTimeout([variable name]) to stop the setTimeout(scrollowanie, 100);
Just assign setTimeout(scrollowanie, 100); to global variable like following:
globalVar = setTimeout(scrollowanie, 100);
And in the console type clearTimeout(globalVar) and the execution will finish
You could wrap desired behaviour in an object that handles the process.
e.g.:
var script = (function () {
var timeout;
var DESIRED_TIME = 100;
function scrollowanie() {
console.log('::Testing');
// Desired behaviour here
clearTimeout(timeout);
timeout = setTimeout(scrollowanie, DESIRED_TIME)
}
return {
start: function() {
timeout = setTimeout(scrollowanie, DESIRED_TIME);
},
stop: function () {
clearTimeout(timeout);
}
}
})();
Then in the command line you will just need to start the process
script.start();
and to end it
script.stop();
I am making a typing game using just jQuery and javascript. It worked fine as a single player game, feel free to play it at http://typetothestars.bitballoon.com/ However, I am planning to keep ratcheting up its complexity level. So I am trying to add muti player to it now.
here it is in jsfiddle minus images https://jsfiddle.net/u32s4yty/
My problem lies in my runRace functions. I was expecting the race to run for player 1, when the interval ended, it would then start again for player 2. Instead, it runs through all the iterations right away. So apperently setTimeout is not going to work here.
Any suggestions as to how to make it work?
Thanks!
// ** RUNNING GAME FUNCTIONS ** \\
//hides instructions and reveals game
function setupRace(i) {
console.log("In Race Setup")
$("#word").show();
document.getElementById("word").focus();
generateWords();
$(".toType").text(gameWords[0]);
$("#instructions").hide();
$(".wordDisplay").show();
$(".player").show();
var playerAvatar = 'url("images/' + playerInfo[i].avatar + '.png")'
$(".player").css({background: playerAvatar});
}
//game timer - IS NOT STOPPING THE OTHER FUNCTIONS FROM RUNNING
var timeoutID;
function timer(i) {
timeoutID = window.setTimeout(checkEndRace, 3000, i)
console.log("i = " + i);
console.log(playerInfo[i]);
}
function checkEndRace(i) {
console.log("in check end race - num players " + numPlayers);
if (i < numPlayers - 1) {
setupRace(i);
}else {
endRace(i);
}
}
//advances ship on correct typing
function runRace() {
console.log("In run race");
var i = 0;
while (i < playerInfo.length) {
console.log("in run race loop");
setupRace(i);
timer(i);
//timer is skipping ahead to the next iteration, eventhough
//checkEndRace hasn't run yet
var j = 1;
$(document).keyup(function(e){
var targetWord = $(".toType").text();
var typedWord = $("#word").val();
while (j < gameWords.length){
if(typedWord === targetWord){
$(".player").css({left: "+=15px",});
targetWord = $(".toType").text(gameWords[j]);
$("#word").val("");
j++;
}else {
return
};
}
});
i ++;
};
}
I was hoping to use setTimeout to stop all functions the following functions, until the interval is completed.
Calls to setTimeout return immediately and only execute once so one easy/common way to handle ordering them is to make tail calls (tick) to setTimeout and to put all requests in a queue.
// ** RUNNING GAME FUNCTIONS ** \\
var raceHandlers = [];
var raceTimout = 3000;
function tick() {
// Tail call
if (raceHandlers.length > 0) {
var action = raceHandlers.pop();
setTimeout(action[0],raceTimeout,action[1]);
}
}
//hides instructions and reveals game
function setupRace(i) {
console.log("In Race Setup")
$("#word").show();
document.getElementById("word").focus();
generateWords();
$(".toType").text(gameWords[0]);
$("#instructions").hide();
$(".wordDisplay").show();
$(".player").show();
var playerAvatar = 'url("images/' + playerInfo[i].avatar + '.png")'
$(".player").css({background: playerAvatar});
tick();
}
//advances ship on correct typing
function runRace() {
console.log("In run race");
var i = 0;
while (i < playerInfo.length) {
console.log("in run race loop");
//setupRace(i);
raceHandlers.unshift([setupRace,i]);
//timer is skipping ahead to the next iteration, eventhough
//checkEndRace hasn't run yet
var j = 1;
$(document).keyup(function(e){
var targetWord = $(".toType").text();
var typedWord = $("#word").val();
while (j < gameWords.length){
if(typedWord === targetWord){
$(".player").css({left: "+=15px",});
targetWord = $(".toType").text(gameWords[j]);
$("#word").val("");
j++;
}else {
return
};
}
});
i ++;
};
raceHandlers.unshift([endRace,playerInfo.length]);
tick();
}
I am using google maps and i am trying to put a pause in execution to prevent QUERY_LIMIT usage issue. My function that plots the addresses looks like this.
The code works, however i want to try setTimeout or setInterval to see if its going to look better on UI.
How do i call it, what should be the first argument?
Thanx alot.
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
//geocode "free" usage limit is 5 requests per second
//setTimeout(PlotAddressesAsUnAssigned, 1000);
//sleep(500);
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
Doing a pause (asynchronous execution) inside a loop (synchronous) will usually result in a lot of trouble.
You can use recursive calls that are done only when a timeout ends.
var vLocations = [];
// Manages the timeout and recursive calls
function AddWaypointAndUnassignedWithPause(index){
setTimeout(function(){
// When the timeout expires, we process the data, and start the next timeout
AddWaypointAndUnassigned(vAddresses[index]);
// Some other code you want to execute
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
if(index < vAddresses.length-1)
AddWaypointAndUnassignedWithPause(++index);
}, 1000);
}
// Start the loop
AddWaypointAndUnassignedWithPause(0);
JSFiddle example.
Try this, hope this will help
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
setTimeout(function(){
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
}, 500);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
What about a waiting line, thats fired when an item is added and stopped when there are no items left.
With setTimeout:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startTimeout();
}
function startTimeout() {
if( to === null ) {
to = setTimout(processLocation, INTERVAL);
}
}
function processLocation() {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
to = setTimout(processLocation, INTERVAL);
} else {
to = null;
}
}
With setInterval:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startInterval();
}
function startInterval() {
if( to === null ) {
to = setInterval(processLocation, INTERVAL);
}
}
function processLocation(cb) {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
} else
clearInterval(to);
to = null;
}
}
I'm trying to make touch controls for a little game I'm writting with the help of jquery. But i just can't figure out how to write a function that basicly does the same thing that happens when you keep a key pressed.
Could you please help me?
PS. its not originaly my code source
jQuery.fn.mousehold = function(timeout, f) {
if (timeout && typeof timeout == 'function') {
f = timeout;
timeout = 100;
}
if (f && typeof f == 'function') {
var timer = 0;
var fireStep = 0;
return this.each(function() {
jQuery(this).mousedown(function() {
fireStep = 1;
var ctr = 0;
var t = this;
timer = setInterval(function() {
ctr++;
f.call(t, ctr);
fireStep = 2;
}, timeout);
})
clearMousehold = function() {
clearInterval(timer);
if (fireStep == 1) f.call(this, 1);
fireStep = 0;
}
jQuery(this).mouseout(clearMousehold);
jQuery(this).mouseup(clearMousehold);
})
}
}
$.fn.extend({
disableSelection: function() {
this.each(function() {
this.onselectstart = function() {
return false;
};
this.unselectable = "on";
$(this).css('-moz-user-select', 'none');
$(this).css('-webkit-user-select', 'none');
});
}
});
Well the question is, how often do you want to check for a change in user input. You are quite limited when it comes to the resolution of a timer in JS. Although be aware that everything is running in sequence and thus events are queued and potentially sum up. This is especially true for setInterval() as it rigorously queues new events, even when previously triggered events were not yet processed.
Something like this works:
var pressed; // flag for continous press between mousedown and timer-events
var duration; // number of times the timer fired for a continous mousedown
var timeout; // reference to timer-event used to reset the timer on mouseup
$(document).mousedown = function(){
pressed = true;
handleMousedown(false);
}
function handleMousedown(continued){
if(pressed){ // if still pressed
if(continued){ // and fired by the timer
duration++;
// measure time, use duration
// do anything
}
timeout = setTimeout('handleMousedown(true)', 100); // wait for another 100ms then repeat
}
}
$(document).mouseup = function() {
// do sth on mouseup
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}
$(document).mouseout = function() { // $(document).mouseenter = function(){
// do sth on mouse leave or mouse entering again according to how your game should behave
pressed = false; // reset flag for continous mousedown
clearTimeout(timeout); // abandon the timer
}
How can I track the browser idle time? I am using IE8.
I am not using any session management and don't want to handle it on server side.
Here is pure JavaScript way to track the idle time and when it reach certain limit do some action:
var IDLE_TIMEOUT = 60; //seconds
var _idleSecondsTimer = null;
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
_idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
window.clearInterval(_idleSecondsTimer);
alert("Time expired!");
document.location.href = "logout.html";
}
}
#SecondsUntilExpire { background-color: yellow; }
You will be auto logged out in <span id="SecondsUntilExpire"></span> seconds.
This code will wait 60 seconds before showing alert and redirecting, and any action will "reset" the count - mouse click, mouse move or key press.
It should be as cross browser as possible, and straight forward. It also support showing the remaining time, if you add element to your page with ID of SecondsUntilExpire.
The above code should work fine, however has several downsides, e.g. it does not allow any other events to run and does not support multiply tabs. Refactored code that include both of these is following: (no need to change HTML)
var IDLE_TIMEOUT = 60; //seconds
var _localStorageKey = 'global_countdown_last_reset_timestamp';
var _idleSecondsTimer = null;
var _lastResetTimeStamp = (new Date()).getTime();
var _localStorage = null;
AttachEvent(document, 'click', ResetTime);
AttachEvent(document, 'mousemove', ResetTime);
AttachEvent(document, 'keypress', ResetTime);
AttachEvent(window, 'load', ResetTime);
try {
_localStorage = window.localStorage;
}
catch (ex) {
}
_idleSecondsTimer = window.setInterval(CheckIdleTime, 1000);
function GetLastResetTimeStamp() {
var lastResetTimeStamp = 0;
if (_localStorage) {
lastResetTimeStamp = parseInt(_localStorage[_localStorageKey], 10);
if (isNaN(lastResetTimeStamp) || lastResetTimeStamp < 0)
lastResetTimeStamp = (new Date()).getTime();
} else {
lastResetTimeStamp = _lastResetTimeStamp;
}
return lastResetTimeStamp;
}
function SetLastResetTimeStamp(timeStamp) {
if (_localStorage) {
_localStorage[_localStorageKey] = timeStamp;
} else {
_lastResetTimeStamp = timeStamp;
}
}
function ResetTime() {
SetLastResetTimeStamp((new Date()).getTime());
}
function AttachEvent(element, eventName, eventHandler) {
if (element.addEventListener) {
element.addEventListener(eventName, eventHandler, false);
return true;
} else if (element.attachEvent) {
element.attachEvent('on' + eventName, eventHandler);
return true;
} else {
//nothing to do, browser too old or non standard anyway
return false;
}
}
function WriteProgress(msg) {
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = msg;
else if (console)
console.log(msg);
}
function CheckIdleTime() {
var currentTimeStamp = (new Date()).getTime();
var lastResetTimeStamp = GetLastResetTimeStamp();
var secondsDiff = Math.floor((currentTimeStamp - lastResetTimeStamp) / 1000);
if (secondsDiff <= 0) {
ResetTime();
secondsDiff = 0;
}
WriteProgress((IDLE_TIMEOUT - secondsDiff) + "");
if (secondsDiff >= IDLE_TIMEOUT) {
window.clearInterval(_idleSecondsTimer);
ResetTime();
alert("Time expired!");
document.location.href = "logout.html";
}
}
The refactored code above is using local storage to keep track of when the counter was last reset, and also reset it on each new tab that is opened which contains the code, then the counter will be the same for all tabs, and resetting in one will result in reset of all tabs. Since Stack Snippets do not allow local storage, it's pointless to host it there so I've made a fiddle:
http://jsfiddle.net/yahavbr/gpvqa0fj/3/
Hope this is what you are looking for
jquery-idletimer-plugin
Too late to reply, but this might help someone to write clean and practical solution. This is an ideal solution, when you do not need to display time left for session expire. Good to ignore setInterval(), which keeps on running the script through out the application running time.
var inactivityTimeOut = 10 * 1000, //10 seconds
inactivitySessionExpireTimeOut = '';
setSessionExpireTimeOut();
function setSessionExpireTimeOut () {
'use strict';
clearSessionExpireTimeout();
inactivitySessionExpireTimeOut = setTimeout(function() {
expireSessionIdleTime();
}, inactivityTimeOut);
}
function expireSessionIdleTime () {
'use strict';
console.log('user inactive for ' + inactivityTimeOut + " seconds");
console.log('session expired');
alert('time expired');
clearSessionExpireTimeout();
document.location.href = "logout.html";
}
function clearSessionExpireTimeout () {
'use strict';
clearTimeout(inactivitySessionExpireTimeOut);
}
Running example: Timeout alert will be popped up in 10 seconds
Here's an approach using jquery as I needed to preserve existing keyboard events on the document.
I also needed to do different things at different idle times so I wrapped it in a function
var onIdle = function (timeOutSeconds,func){
//Idle detection
var idleTimeout;
var activity=function() {
clearTimeout(idleTimeout);
console.log('to cleared');
idleTimeout = setTimeout(func, timeOutSeconds * 1000);
}
$(document).on('mousedown mousemove keypress',activity);
activity();
}
onIdle(60*60,function(){
location.reload();
});
onIdle(30,function(){
if(currentView!=='welcome'){
loadView('welcome');
}
});
I needed a similar thing and created this :https://github.com/harunurhan/idlejs
It simple, configurable and powerful in a way, without any dependencies. Here's an example.
import { Idle } from 'idlejs/dist';
// with predefined events on `document`
const idle = new Idle()
.whenNotInteractive()
.within(60)
.do(() => console.log('IDLE'))
.start();
You can also use custom event targets and events
const idle = new Idle()
.whenNot([{
events: ['click', 'hover'],
target: buttonEl,
},
{
events: ['click', 'input'],
target: inputEl,
},
])
.within(10)
.do(() => called = true)
.start();
(Written in typescript and compiled to es5)