Laravel jquery javascript localStorage - javascript

Problem is my timer was working as well. But when i save timers value to localStorage. I just want to when user refresh timer wont stop and resume when stopped at.
javascript
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){ document.myform.submit(); }
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
var startTime = document.getElementById("timer").value;
localStorage.setItem("startTime", startTime);
//alert(startTime);
}
function Dahin(){
var startTime = localStorage.getItem("startTime");
document.getElementById('timer').value = startTime;
}
in my view
<h3 onload="Dahin();" class="page-title">Шалгалтын 50 асуулт</h3><h4><div>Үлдсэн хугацаа = <span id="timer">{{ $time }}</span></div></h4>
Update fixed timer
now how to save timer value to sessionstorage and retrieve when refresh page

Let change your code:
var check = localStorage.getItem("startTime");
var startTime = check ? check : document.getElementById("timer").innerHTML;
document.getElementById('timer').value = startTime;
function Dahin(){
localStorage.setItem("startTime", startTime);
}
the problem why you get null is because you use .value. You put your time into span tag. .value is only work for input field

Related

Javascript clearInterval is not having an effect?

I am trying to do a simple redirect after x seconds on a page with a countdown timer. Every time I call the function I want the timer to be reset, however when i call it a second or third time the timer seems to have 3 different countdowns. Can anyone see why this is?
function delayRedirect(){
document.getElementById('countDown').innerHTML = 'Session Timeout In: <span id="countTimer"></span> seconds....';
clearInterval(sessionTimer);
var sessionTimer = null;
var timeleft = 60;
var sessionTimer = setInterval(function(){
timeleft--;
document.getElementById('countTimer').innerHTML = timeleft;
if(timeleft <= 0)
clearInterval(sessionTimer);
returnToLogin();
},1000);
}
Put the sessionTimer globally. What you currently do is re-declare sessionTimer every time you enter delayRedirect.
Working example:
const but = document.getElementById("but");
but.addEventListener("click", delayRedirect);
//define it globally
var sessionTimer = -1;
function delayRedirect() {
//clear it if it previously exists
clearInterval(sessionTimer);
sessionTimer = setInterval(function() {
console.log("sessionTimer " + sessionTimer);
}, 1000);
}
<button id="but">Run</button>
I feel like all the answers only address the Y part, not the X part, given that this is clearly an XY problem.
While the solution is to use a variable that isn't local to the function, solving the actual problem doesn't require clearing anything. One can simply use an interval to tick down, and reset the count to delay the redirect:
var timeleft = 60;
setInterval(function() {
if (--timeleft === 0) returnToLogin();
countTimer.innerHTML = timeleft;
}, 1000);
delay.onclick = function() {
timeleft = 60;
}
function returnToLogin() {
console.log("returning to login");
}
<p>Session Timeout In: <span id="countTimer">60</span> seconds....</p>
<button id="delay">Delay</button>

how to create click event to display set interval time

I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.
let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}
This should solve your problem.
var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");
timeElement.innerHTML = timeSpent;
let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);
document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>
First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.
Your code should look something like this
let timerId;
function displayTime() {
timerId = setInterval(() => {
// your code
}, 1000);
}
document.querySelector('button').addEventListener('click', displayTime)

Log the time in between user - a simple timer

I'm trying to create a simple timer.
The user presses a 'start' button. When the user presses another button, I would like to log the time in between.
Could this be achieved with setTimeout?
setTimeout shouldn't be used for your situation. The following is a method to display the amount of seconds between clicking "startBtn" and then clicking "endBtn":
var date1 = new Date();
document.getElementById("startBtn").onclick = function(){
date1 = new Date();
}
document.getElementById("endBtn").onclick = function(){
var date2 = new Date();
var dif = date1.getTime() - date2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
alert(Seconds_Between_Dates);
}
You can build from here to get your desired functionality (for example, if the user clicks "endBtn" before clicking "startBtn", the results are inaccurate, of course. You can fix by disabling buttons as needed, etc.)
(thanks to How Many Seconds Between Two Dates?)
It's really not necessary to use a Timeout for this. All you want to do is measuring two difference between two time dates.
HTML:
<span class="startTimer">
Start Timer
</span>
<span class="stopTimer">
Stop Timer
</span>
<span class="result">
</span>
JS, and no, the use of JQuery is not needed here but I like the way it handles events:
(function($){
var Timer = {
startTimeInMs: null,
endTimeInMs: null,
start: function(){
this.startTimeInMs = new Date();
},
stop: function(){
this.endTimeInMs = new Date();
},
getTime: function(){
return this.endTimeInMs - this.startTimeInMs;
},
bind: function() {
var self = this;
$('.startTimer').on('click', function(){
self.start();
});
$('.stopTimer').on('click', function(){
self.stop();
self.printResult();
});
},
printResult: function() {
$(".result").html(this.getTime())
},
init: function(){
this.bind();
}
}
var timer = Object.create(Timer);
timer.init();
})(jQuery);
You can just use the Date.now() method, there's no need to instantiate a new Date object each time.
Here's a jsFiddle that measures lap times as an example: http://jsfiddle.net/ZpFnp/
HTML
<button id="start">start/reset</button>
<button id="stop">lap</button>
<div id="output"></div>
JavaScript
var startTime = Date.now();
document.getElementById("start").addEventListener("click", function () {
document.getElementById("output").innerHTML = "";
startTime = Date.now();
});
document.getElementById("stop").addEventListener("click", function () {
var elapsedTime = Date.now() - startTime;
document.getElementById("output").innerHTML += "<p>" + elapsedTime + "</p>";
});

Getting contents of dynamic Iframe

I am trying to get the contents of a dynamically generated Iframe (same-domain). I have this so far.
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().attr('title');
var getTime = setInterval(function() {
var newTime = $('.date-and-time , frame.contents()').last().attr('title');
},500);
I tried lines 1 and 2 together with an alert of time to see if I was actually grabbing the data. Though I am not. Basically what I want to do is get the last message .data-and-time and with the setInterval get the same thing.
If they are different do something.
This is how I believe my code will be set up once i get the data
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().attr('title');
var getTime = setInterval(function() {
var newTime = $('.date-and-time , frame.contents()').last().attr('title');
},500);
if(time === newTime) {
alert();
}
Any suggestions on grabbing data from iframe?
Also tried=
var frame = $('#avacweb_chat iframe');
var time = $(frame).contents($('.date-and-time'));
alert(time.length);
Which I get 1 which is correct
Then I tried
var frame = $('#avacweb_chat iframe');
var time = $(frame).contents($('.date-and-time').attr('title'));
alert(time);
Which becomes [object Object]
Working code =
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().attr('title');
var newTime = setInterval(function() {
var newT = $('.date-and-time' , frame.contents()).last().attr('title');
},500);
if(time !== newT) {
alert('New Message');
}
Now my question would be how do I get the newTime store it and then compare them?
Maybe it's a race condition. Would it be possible that your iFrame hasn't completely loaded at the time you're trying to traverse the DOM? Give this a shot:
var frame = $('#avacweb_chat iframe'),
newTime;
frame.on('load', function(){
newTime = frame.contents().find('.date-and-time').attr('title');
});
alert(newTime);

Countdown timer for use in several places at same page

I want to make a countdown timer, that can be used on several places in the same page - so I think it should be a function in some way.
I really want it to be made with jQuery, but I cant quite make it happen with my code. I have e.g. 10 products in a page, that I need to make a countdown timer - when the timer is at 0 I need it to hide the product.
My code is:
$(document).ready(function(){
$(".product").each(function(){
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
var elm = $(this).attr('id');
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
EDIT 1:
$(document).ready(function(){
$(".product").each(function(){
var elm = $(this).attr('id');
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
Do you have any solutions to this?
I'd probably use a single interval function that checks all the products. Something like this:
$(function() {
/* set when a product should expire.
hardcoded to 5 seconds from now for demonstration
but this could be different for each product. */
$('.product').each(function() {
$(this).data('expires', (new Date()).getTime() + 5000);
});
var countdown_id = setInterval(function() {
var now = (new Date()).getTime();
$('.product').each(function() {
var expires = $(this).data('expires');
if (expires) {
var seconds_remaining = Math.round((expires-now)/1000);
if (seconds_remaining > 0) {
$('.time-left', this).text(seconds_remaining);
}
else {
$(this).hide();
}
}
});
}, 1000);
});
You could also cancel the interval function when there is nothing left to expire.
Your problem seems to be that this doesn't refer to the current DOM element (from the each), but to window - from setTimeout.
Apart from that, you have an unnecessary domReady wrapper, forgot the # on your id selector, should use cached references and never rely on the timing of setInterval, which can be quite drifting. Use this:
$(document).ready(function(){
$(".product").each(function(){
var end = new Date(/* from something */),
toUpdate = $(".time_left", this);
prod = $(this);
countDown();
function countdown() {
var cur = new Date(),
left = end - cur;
if (left <= 0) {
prod.remove(); // or .hide() or whatever
return;
}
var sec = Math.ceil(left / 1000);
toUpdate.text(sec + " seconds remaining!"); // don't use .html()
setTimeout(countdown, left % 1000);
}
});
});

Categories

Resources