This question might already been discussed but I couldn't find quite what I was looking for.
I'm working on Adobe Edge Animate with HTML+JS. This is a full JS question so that's why I'm posting it here. I wrote a bit of code to have dialogue box appear at a specific time during the day. The dialogue has two buttons: "Play Video Now" and "Remind me in 10 mins"
Here is the code:
function updateClock() {
var d = new Date(); // current date
var m = d.getMinutes();
var h = d.getHours();
console.log(h, ":", m);
// call this function again in 1000ms
sym.updateClock = setTimeout(updateClock, 1000);
if (h == 9 && m == 0) { //at 9hrs 00 min
//run the dialogue for the morning pause
sym.play(1000);
} else {
sym.stop(1000);
}
}
updateClock(); // initial call
Then I have to bind the snooze button so it adds 10 minutes to my conditional statement. I know I have to add some sort of "count" variable, but I don't know exactly how to do it.
(function(symbolName) {
Symbol.bindElementAction(compId, symbolName, "${_snoze_btn}", "click", function(sym, e) {
}
pretty sure you just want this -
(function(symbolName) {
Symbol.bindElementAction(compId, symbolName, "${_snoze_btn}", "click", function(sym, e) {
// remind again again in 10 minutes
popupPlayOrSnoozeDialogTimer = setTimeout(popupPlayOrSnoozeDialogTimer, 600000);
});
}())
If you want to add 10 minutes to the current timeout until that function is called again, check out this answer or look at new Date().valueOf()
Related
I am working on a personal project and I am making use of JS to implement a simple countdown timer. There are several requirements that need to be addressed:
- The timer starts when the page is loaded
- When the user wishes to leave the page, they are warned that their progress will be lost, hence, the timer is reset.
I am making use of localStorage to keep the remaining time, since every time the user submits a form that is on the page, the page is reloaded (I understand that it is better to use AJAX, but for the time being, I am trying to make it work properly as it is). You can see my code below:
var submit_form;
var timeLeft;
function startTimer(duration, content) {
var timer = duration, min, sec;
setInterval(function () {
if (--timer < 0) {
//redirect here;
submit_form = true;
localStorage.removeItem("remainingTime");
window.location.replace("some url");
} else {
min = parseInt(timer / 60, 10);
sec = parseInt(timer % 60, 10);
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
localStorage.setItem("remainingTime", timer);
console.log(timer);
content.textContent = min + ":" + sec;
}
}, 1000);
}
window.onload = function () {
submit_form = false;
console.log(submit_form);
if (localStorage.getItem("remainingTime")) {
timeLeft = localStorage.getItem("remainingTime");
} else {
timeLeft = 60;
}
var display = document.querySelector('#time');
startTimer(timeLeft, display);
};
window.onbeforeunload = function () {
if (submit_form != true) {
localStorage.removeItem("remainingTime");
window.localStorage.clear();
return "You will lose all your progress!/nAre you sure you want to quit?";
}
};
'submit_form' is used for controlling when 'onbeforeunload' gets triggered - When the user submits the form, it shouldn't trigger.
<button type="submit" name="submit" value="Search" id="search-button" onclick="submit_form = true;">Submit</button>
The issue that I am facing, which is killing me, is that sometimes when the user tries to leave the page, i.e. 'onbeforeunload' is triggered, the localStorage doesn't always clear. Therefore, when they come back to the page, the timer doesn't start from the beginning, but instead, from where they left off.
I have tried a few variations of the code above, and my best guess is that setInterval() might be the reason for localStorage not clearing every time.
I need to create a timer and want to measure the time from Clicking OK to start till the user clicks OK stop. I just want to display the time difference between clicking the OK's. Does anyone know how to do this as simply as possible? Although it may seem easy for most of you i'm really sturggling to work it out, any help is appreciated
var canvas;
canvas = openGraphics();
alert( "Press \"OK\" to start the timer." );
alert( "Press \"OK\" to stop the timer." );
canvas.paint();
http://jsfiddle.net/g74ssnku/1/
alert("ok start")
var starttime = Date.now();
alert("ok stop")
var stoptime = Date.now();
var seconds_between = (stoptime - starttime)/1000 ;
alert(seconds_between + " seconds");
Just record the time between the two confirmations and you should be fine.
Have an OK button, perhaps:
<input type="button" id="the-button" value="OK">
In a script tag somewhere after that HTML (at the end of the document is good), have a timer variable which is initially 0:
var timer = 0;
...and add an event handler for the button:
document.getElementById("the-button").addEventListener("click", function() {
// ...we'll add more here in a moment...
}, false);
When the user clicks the button, if timer is 0, record the starting time; if not, report the difference and reset it to 0:
document.getElementById("the-button").addEventListener("click", function() {
var elapsed;
if (timer === 0) {
timer = Date.now();
} else {
elapsed = Date.now() - timer; // In milliseconds
alert("Elapsed time: " + elapsed); // Or whatever you want to do with it
timer = 0;
}
}, false);
Live Example:
(function() {
"use strict";
var timer = 0;
document.getElementById("the-button").addEventListener("click", function() {
var elapsed;
if (timer === 0) {
timer = Date.now();
} else {
elapsed = Date.now() - timer; // In milliseconds
alert("Elapsed time: " + elapsed);
timer = 0;
}
}, false);
})();
<input type="button" id="the-button" value="OK">
Note: That uses addEventListener, which is supported by all modern browsers (including IE9). To support old IE (such as IE8), you'll have to handle the fact that it uses attachEvent instead of addEventListener. Similarly, Date.now is not in IE8, but can be polyfilled for old browsers:
if (!Date.now) {
Date.now = function() {
return +new Date();
};
}
Sorry for that short and meaningless title, but it really is the only one that really describes my problem.
I want (or have to) script a slideshow which (if a checkbox is checked and a time is given) automatically switches the focus on another image.
I already have everything but the automation and am currently working on it.
I thought that comparing the current time with a target time (currentTime + user-input seconds (in Integer)) every 1000 millisecs would be the best way to do it.
However, I don't get why, but it's not working. The calculated target time seems to be correct, since I get a correct difference of the pre-calculated date.getTime() and the calculated one.
I would be very thankful if you could help me.
Here's the JS:
var checkbox_checked;
function timerfn() {
if (checkbox_checked === null || checkbox_checked === false) {
checkbox_checked = true;
var targetTime = new Date();
alert(targetTime.getTime());
var target_sec = targetTime.getSeconds() + dauerSwitch;
targetTime.setSeconds(target_sec);
alert(targetTime.getTime());
// update currentTime every 1 Seconds (1000 Milliseconds)
setInterval(function () {
var current_time = Date.now();
if (targetTime.getTime() == current_time) {
gallery("zur");
}
}, 1000);
} else {
checkbox_checked = false;
}
}
And here's the HTML:
<form>
<input type="checkbox" id="timer" name="timer" onClick="timerfn()">
<input type="text" id="textbox" name="timerParam"
placeholder="Seconds between slides" value=""
onBlur="boxConv()"> //boxConv just converts the String to an Integer. It also checks if it's only numbers
</form>
Thats how i would do it with a little help of jquery ($). I moved the inline code into JS event listener and used the user input as parameter for the interval to make it work.
$(function () {
var intervalTime = 1000,
counter = 1,
interval;
$("#textbox").on("blur", function () {
var inputValue = $(this).val();
try {
//parses the user input into a integer
intervalTime = parseInt(inputValue, 10) * 1000;
} catch (e) {
//could not parse input
}
});
$("#timer").on("click", function () {
if ($(this).is(":checked")) {
interval = setInterval(function () {
//gallery("zur");
//fills the test output
$("#testOutput").val(counter);
counter++;
}, intervalTime); //intervall time is given in milliseconds
} else {
clearInterval(interval);
}
});
});
And here the link to a working example:
http://jsfiddle.net/9Yeuh/2/
I'm unable to figure out where a syntax logical error resides in the script furthest below. Essentially what it does is it alerts people that they must wait 1.5 seconds before they can answer a radio-button type question and automatically move on to the next page. No alert if they spend more than 1.5 seconds.
This script was written for only one click event, but I need it to work for two nested events, where clicking on a radio button option automatically triggers the "next" button to move on to the next page. For example if you take out the following event (and its end brackets), it works well:
$("[class*=bfasg] .radio").click(function(){
I've checked the syntax at Esprima to make sure the brackets are correct, so the problem lies elsewhere.
$(document).ready(function() {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
$("[class*=bfasg] .radio").click(function(){$("#movenextbtn").click(function(){
var endTime = new Date();
if((endTime - startTime)/1000 <= minTime) {
alert('You must spend at least '+minTime+' seconds on the question.');
return false;
}
else {
return true;
}
});
});
}
});
Any experts out there who can detect the problem?
(See answer to updated question below)
It's not a syntax error. It's a logic error.
It becomes slightly clearer if you format the code consistently:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
// Hooking up a click handler
$("[class*=bfasg] .radio").click(function () {
// This code doesn't run until/unless someone clicks
// one of the `[class*=bfasg] .radio` elements.
$("#movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
} else {
return true;
}
});
});
}
});
What you've done there is said "When someone clicks a [class*=bfasg] .radio element, hook up an event handler on the #movenextbtn element."
You probably don't want to wait to hook up the event until someone clicks on a radio button. If your goal is to hook up the click event on both sets of elements, combine them in the same selector as you would in CSS:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
$("[class*=bfasg] .radio, #movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
}
});
}
});
(By the way, returning true from a jQuery event handler has no meaning, so I've removed it above.)
Below you've commented:
What happens is that I want clicking the radio button to automatically trigger the "Next" button for going to the next page since I have one question per page.
That doesn't fundamentally change things. You haven't shown what the button does to move to the next page, but you'd just put that code in the one click handler above. E.g., you still hook click on both the radio buttons and the button, and you still handle that event using common code. E.g.:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
$("[class*=bfasg] .radio, #movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
} else {
// ****Move to next page here****
}
});
}
});
Alternately, you could have the radio button click trigger a click event on the button, like this:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
// Hook up `click` on the radio buttons
$("[class*=bfasg] .radio").click(function () {
// Respond to click by firing click on the #movenextbtn
$("#movenextbtn").click();
});
// Hook up `click` on the #movenextbtn
$("#movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
}
});
}
});
I'm not a huge fan of firing synthetic events like that when you could use common logic, but it's an option.
function callMe() {
// Do Something
}
$(document).ready(function() {
callMe();
});
DECLARE FUNCTION outside of ready(), but then define FUNCTION inside of ready().it's better to define them outside of document ready. And, if you need to, place the implementation of the method within the document ready.
I have this button which is not working correctly for hold button for a period (but it works like click only).
Where i was trying to do if the button is hold for greater/equal then 2 seconds then callfunction1, if the button was pressed less then 2 seconds then callfuntion2.
var clickDisabled = false;
function clickLocker() {
/* #Button: 2 seconds */
clickDisabled = true;
setTimeout(function(){clickDisabled = false;}, 2000);
}
function callfunction1() { // you have hold he button for greater then or equal 2 second }
function callfunction2() { // you have hold the button less then 2 second }
$('.button').live("click",function()
{
if (clickDisabled) {
alert("locked for 2 second");
return;
}
clickLocker();
});
I think this solution should work. I have not tested it but it should give you the right idea.
var startTime;
function callfunction1() { // you have hold he button for greater then or equal 2 second }
function callfunction2() { // you have hold the button less then 2 second }
function buttonDownEvent() {
var Time = new Date();
startTime = Time.getTime();
}
function buttonUpEvent() {
if(new Date().getTime() - startTime < 2000)
callfunction2()
else
callfunction1()
}
$('.button').live("mousedown",function()
{
buttonDownEvent();
});
$('.button').live("mouseup",function()
{
buttonUpEvent();
});
Listen for both events, mousedown and mouseup, measuring the time between both:
var timeDown;
var timeUp;
$('.button').live("mousedown",function(){
timeDown = event.timeStamp;
});
$('.button').live("mouseup",function(){
timeUp = event.timeStamp;
time = timeUp-timeDown;
if (time>2000){
function1();
}else{
function2();
}
});
please note that event.timeStamp wont work well in firefox. For firefox you can do (new Date).getTime();
You can do this using events to the mouseup and mousedown events and timing the difference between them. Also, you need to remember which element caused the click - if the user released the mouse on a different element then it should just do the "non 2-second hold" function. A JSFiddle showing this working is available here: http://jsfiddle.net/35rw3/6/.
That was a great suggestion from slash. This is how you can do this
var clickstart;
var clickstop;
$("a").on('mousedown', function(e) {
clickstart = e.timeStamp;
}).on('mouseup', function(e) {
clickstop = e.timeStamp- clickstart
if(clickstop >= 2000) two()
else one();
});
Demo
Updates:
It might be necessary to track the mouse movement like #MarkRhodes wrote in his comments. So for that, check this update