I'm trying to add to this code so it will auto-run the string for button.g == 1, after 10 seconds of not clicking the button.
{
if(button.g == 0)
{
f.a(parent);
AutoJoin.instance.resetCache();
}
if(button.g == 1)
{
AutoJoin.instance.screen = new AutoJoinScreen(parent, info);
f.a(AutoJoin.instance.screen);
}
if(button.g == 2)
f.a(new PropertiesScreen(this, info.ip));
}
You can use setTimeout to "delay" an action:
setTimeout(function() { console.log('I'm 10 secs later'); }, 1000*10);
With clearTimeout you can abort such a timer:
var timer = setTimeout(/* .... */);
clearTimeout(timer)
In your example you could start a timeout which executes the logic for button.g == 1 and cancel the timer if any button is clicked:
Setting the timer to 10s:
var timer = setTimeout(1000*10, function() {
AutoJoin.instance.screen = new AutoJoinScreen(parent, info);
f.a(AutoJoin.instance.screen);
})
Click routine:
clearTimeout(timer);
if(button.g == 0) {
f.a(parent);
AutoJoin.instance.resetCache();
}
else if if(button.g == 1) {
AutoJoin.instance.screen = new AutoJoinScreen(parent, info);
f.a(AutoJoin.instance.screen);
}
else if(button.g == 2) {
f.a(new PropertiesScreen(this, info.ip));
}
Related
I have a function that will perform an action when the timer reaches 5000ms:
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
//I am trying to loop this 5 times with the 5000ms delay - the code I am using for this is:
for (i=0;i<=5;i++)
{
MyFunc();
}
It seems regardless of whether I put the for loop in the timer or whether I put the timer inside the for loop the result is the same where all 5 loops happen instantaneously instead of with a delay of the timer being applied? I'm not sure what i'm doing wrong here... Any help would be appreciated!
Sorry, edit to include the complete code below:
<script>
var iframe2 = document.getElementById('postbid_if');
function isElementInViewport() {
var el = document.getElementById('postbid_if')
console.log(el)
var rect = el.getBoundingClientRect();
console.log(rect)
return rect.bottom >= 0 &&
rect.right >= 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) &&
rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
function Timer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function () {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
this.resume = function () {
start = new Date();
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
}
for (i = 0; i <= 5; i++) {
MyFunc();
}
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
</script>
It's because it's looping through quickly 5 times then all 5 loops are delaying after the 5 seconds. The timeout pauses it after 5 seconds, not for 5 seconds up front.
Perhaps you could revise your code in this way to achieve the timer based iterations as required:
//Track the current iteration
var i = 0;
function MyFunc() {
var timer = new Timer(function () {
console.log("refreshingBid");
refreshBid();
// The current timer has completed. If the current
// iteration is less than 5...
if(i < 5) {
i++;
// .. then start another timer for the next iteration
MyFunc();
}
}, 5000);
timer.pause();
if (isElementInViewport() === true) {
console.log("element in view");
timer.resume();
} else {
timer.pause();
console.log("element is out of view")
}
}
// Start the first iteration
MyFunc();
I'm currently working on a short quiz game but I cant seem to figure it out. I feel like I have everything that I need, but I may have possibly placed them in a wrong order?
JS:
function stopTimer() {
clearInterval(intervalID);
}
function startTimer() {
intervalID = window.setInterval(function() {
animations()
}, 1000);
time = 30;
}
animations = function() {
time--;
if (time >= 0) {
timer.textContent = time;
} else if (time == 0) {
EndToAlert(); //*This is the function im trying to fire once timer
reaches 0 * //
stopTimer();
}
}
Use if (time == 0) instead of else if (time == 0), because when time=0, the if (time >= 0) above will be executed but the else if (time == 0) won’t.
just change else if (time == 0) to else.
I want if I call my second if else work then first one should stop. But that also keep running. If first one running second should stop.
if(e.keyCode == 39) {
setInterval(function(){
//
}, 10);
} else if(e.keyCode == 37) {
setInterval(function(){
//
}, 10);
}
setInterval() returns the ID of the set timer, that can be used to stop it.
Something like this should work:
var intervalId1, intervalId2;
if(e.keyCode == 39) {
intervalId1 = setInterval(function() { ... }, 10);
if (intervalId2) {
clearInterval(intervalId2);
}
} else if(e.keyCode == 39) {
intervalId2 = setInterval(function() { ... }, 10);
if (intervalId1) {
clearInterval(intervalId1);
}
}
You need to use a variable which is in a shared scope
//in a shared scope, probably outside teh function where this code is placed
var interval;
if (e.keyCode == 39) {
if (interval) {
clearInterval(interval);
}
interval = setInterval(function () {
//
interval = undefined;
}, 10);
} else if (e.keyCode == 37) {
if (interval) {
clearInterval(interval);
}
interval = setInterval(function () {
//
interval = undefined;
}, 10);
}
setInterval returns a handle which you can use to stop/clear the interval.
It is also important that you store this handle outside the function itself, or else it will be cleared next time the function runs.
Since you only care about one interval to run, you also only need to store one handle.
//define globally outside your function
var interval = null;
//your function starts here
interval && clearInterval(interval); // (same as if(interval){clearInterval(interval);})
if(e.keyCode == 39) {
interval = setInterval(function(){
//
}, 10);
} else if(e.keyCode == 37) {
interval = setInterval(function(){
//
}, 10);
}
Using one variable interval to store the return id of setInterval and whenever call to function clear that interval you will get what you need.
var interval;
$("#text_box").keydown(function(e){
e.preventDefault();
if(e.keyCode == 39){
clearInterval(interval);
interval=setInterval(sample1,1000);
}
else if(e.keyCode == 37){
clearInterval(interval);
interval=setInterval(sample2,1000);
}
});
function sample1(){
console.log("1");
}
function sample2(){
console.log("2");
}
function testworking(n){
if(n == 1)
testuser();
else
testconfig();
}
setInterval(function(){testworking(n)}, 1000);
How do I make that function testuser(); could not start earlier than 10 seconds after the previous launch?
P.S.:
an approximate algorithm:
if(n == 1){
if (first run function `testuser()` ||
time after previous run `testuser();` == 10 seound){
testuser();
}
}
Set a flag using a timer:
var is_waiting = false;
function testuser() {
if (!is_waiting) {
//do your stuff here
} else {
alert('You must wait ten seconds before doing this again');
}
is_waiting = true;
setTimeout(function() {is_waiting = false}, 10000);
}
You can do it like this
var i = 0;
function testworking(i){
if(i < 10) {
console.log(i);
} else {
console.log('Here is 10 second');
}
}
setInterval(function(){
i = (i == 10) ? 0 : i;
i++;
testworking(i);
}, 1000);
It's not entirely clear what you're looking for, but here's something that might give you an idea.
var n = 1;
var testUserInterval;
function testworking(n) {
if (n == 1)
testuser();
else
testconfig();
}
function testuser() {
var cnt = 0;
if (testUserInterval == null) {
testUserInterval = setInterval(function() {
document.getElementById("testusercnt").innerHTML = cnt;
cnt += 1;
if (cnt == 10) {
clearInterval(testUserInterval);
testUserInterval = null;
//DO SOMETHING ???
testuser();
}
}, 1000);
}
}
function testconfig() {
document.getElementById("testconfig").innerHTML = n;
}
setInterval(function() {
testworking(n++)
}, 1000);
testuser cnt:<span id="testusercnt"> </span>
<br/>testconfig n: <span id="testconfig"> </span>
I want to check if Enter key was pressed twice within 5 secs and perform some action.
How can I check if the key was pressed once or twice within a given time and perform different actions.
Here is my code:
<h1 id="log">0</h1>
<br/>
<span id="enteredTime">0</span>
<script>
$(document).keypress(function(e) {
if(e.which == 13){
var element = $("#log");
var timeDifference = 0;
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
//Check if enter was pressed earlier
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
//Check if enter was pressed only once within 5 secs or more
if(){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
});
</script>
http://jsfiddle.net/Rjr4g/
Thanks!
something like
var start=0;
$(document).keyup(function(e) {
if(e.keyCode == 13) {
elapsed = new Date().getTime();
if(elapsed-start<=5000){
//do something;
}
else{
//do something else;
}
start=elapsed;
}
});
Try a timer based solution like
var flag = false,
timer;
$(document).keypress(function (e) {
var element = $("#log");
var timeDifference = 0;
if (e.which == 13) {
if (flag) {
console.log('second');
clearTimeout(timer);
flag = false;
} else {
console.log('first');
flag = true;
timer = setTimeout(function () {
flag = false;
console.log('timeout')
}, 5000);
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
Demo: Fiddle
Bacon.js seems like a good tool to express this.
$(document).asEventStream('keypress')
.filter(function (x) {
return x.keyCode == 13;
})
.map(function () {
return new Date().getTime();
})
.slidingWindow(2, 1)
.map(function (x) {
return (x.length == 1 || x[1] - x[0] > 5000) ? 1 : 2;
})
.onValue(function (x) {
$("#log").text(x == 1 ? "Once" : "Twice in less than 5 secs");
});
(fiddle)
here is my solutions, please check it if match your idea :)
(function($){
var element = $("#log");
var timeDifference = 0;
var count = 0;
$(document).keypress(function(e) {
if(e.which === 13){
//do what you want when enterpress 1st time
/*blah blah */
//after done 1st click
count++;
if(count === 2) {
//do what you want when enterpress 2nd time in 5 seconds
/* blah blah */
//after done
clearTimeout(watcher);
count = 0;
return;
}
//setTimeout to reset count if more than 5 seconds.
var watcher = setTimeout( function() {
count = 0;
},5000);
}
});
}(jQuery)
Check your Updated Fiddle
var count = 0;
$(document).keypress(function(e) {
var element = $("#log");
var timeDifference = 0;
if(e.which == 13){
count++;
console.log('enter pressed'+count);
if(count == 1){
startTimer();
}
else{
checkCount();
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
function startTimer(){
setTimeout(checkCount,5000);
}
function checkCount(){
if(count == 1){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
startTimer() starts counting on first enter press. And checkCount() contains your condition after 5secs.
setTimeout() lets you attach an event which occurs after a specific timespan.