jQuery continues even if user has left the page - javascript

I want to make a page that runs a jQuery script when user gets in the page and the query runs even if user leaves the page or closes the browser. Is this possible?
if(localStorage.getItem("counter")){
if((localStorage.getItem("counter") >= 300) || (localStorage.getItem("counter") <= 0)){
var value = 300;
}else{
var value = localStorage.getItem("counter");
}
}else{
var value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function (){
if(value <= 0){
localStorage.setItem("counter", 0);
value = 0;
$( ".exit" ).trigger( "click" );
}else{
value = parseInt(value)-1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function (){counter();}, 1000);
This is my script. For more detail, this is a countdown from 300 that when user gets in the page it starts and I want to make it like it runs even if user has left the page till it gets 0.

I dare to answer your question and nevertheless hope this will help you. There is no chance to run this js-code after this tab has been closed but you can remember the time an user left your site by setting a time_leave that is set on each interval-round and when an user leaves your site using onbeforeunload:
var value;
if (localStorage.getItem('counter')) {
if ((localStorage.getItem('counter') >= 300) || (localStorage.getItem('counter') <= 0)) {
value = 300;
} else {
value = getElaspedTime();
}
} else {
value = 300;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function () {
if (value <= 0) {
localStorage.setItem('counter', 0);
value = 0;
//$('.exit').trigger('click');
} else {
value = parseInt(value) - 1;
localStorage.setItem('counter', value);
}
document.getElementById('divCounter').innerHTML = value;
// set "departure"-time
localStorage.setItem('time_leave', (new Date()).getTime());
};
function getElaspedTime() {
var now = new Date();
var timeLeft = + localStorage.getItem('time_leave');
timeLeft = new Date(timeLeft);
var passedSecs = (now.getTime() - timeLeft.getTime()) / 1000;
return parseInt(localStorage.getItem('counter')) - parseInt(passedSecs);
}
window.onbeforeunload = function(){
// set "departure"-time when user closes the tap
localStorage.setItem('time_leave', (new Date()).getTime());
};
var interval = setInterval(function () {
counter();
}, 1000);

Related

Restart Timer Using Javascript

I try to use JavaScript to set timer for my quiz.(setInterval) but if I finish the quiz earlier and click on start button gain, the time will start counting at the time I stop the quiz. How can I restart the time after I click on the start button again? .
<script>
var seconds = 40;
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = seconds;
alert(value);
} else {
var value = localStorage.getItem("counter");
}
} else {
var value = seconds;
}
document.getElementById("divCounter").innerHTML = value;
var counter = function() {
if (value <= 0) {
localStorage.setItem("counter", seconds);
value = seconds;
} else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
document.getElementById("divCounter").innerHTML = value;
};
var interval = setInterval(function() { counter(); }, 1000);
</script>
Based on your current code what you need to do to reset the counter is set value=seconds and removing the current value in localStorage.
So assuming you have a button like this in your HTML:
<button type"button" onclick="resetCounter()">Reset</button>
you can add a resetCounter() function in your code:
var resetCounter = () => {
value = seconds;
localStorage.removeItem("counter");
};

Insert two scripts in the same <script> tag without conflicts

I have to put these two scripts in a single tag without them coming into conflict but I can not make it. Please, how can I do it?
Also is it better to insert multiple scripts in the same tag?
Script 1
var sec = 04;
var hour = 00;
var time0, time1;
var delay=0;
var duringtime = 1000;
time1 = (hour *10000 + min * 100 + parseInt(sec)).toString();
console.log("time1", time1);
function refresh() {
........
}
}
refresh();
Script 2
var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (max - min)) + min;
if (localStorage.getItem("stockcount_99")) {
if (localStorage.getItem("stockcount_99") >= duration) {
var value = random;
} else {
var value = localStorage.getItem("stockcount_99");
}
} else {
var value = random;
}
document.getElementById('divCounter').innerHTML = value;
var stockcount_99 = function() {
if (value <= stopValue) { // end count down. <= or >=
clearInterval(interval);
value = stopValue;
} else {
value = parseInt(value) - 1; // + 1 or - 1
localStorage.setItem("stockcount_99", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() {
stockcount_99();
}, speedcontrol);
With the following method can I isolate the two scripts and thus prevent any conflicts?
(function() {
...script 1...
})()
(function() {
...script 2...
})()

Increment issues

I have a timer going that adds 1 every second to the variable MenuTimer.
What I want is when the next button is pressed TillOpen The MenuTimer will stop having 1 added to it after that and a new variable to have 1 added instead PackTime
window.onload = function () {
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var Interval;
var menuTime;
var serviceTime;
var orders;
var menuAvg;
var serviceAvg;
StartButton.onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
function startTimer () {
StopwatchSeconds++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
ShowMinutes.innerHTML = StopwatchMinutes;
StopwatchMinutes++;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
}
Here's all of it. It half works but hopefully you get a better Idea of what i'm trying to go for.
var Interval;
var PackInterval;
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var TillOpenButton = document.getElementById("TillOpen");
var FinishButton = document.getElementById("Finish");
var ShowMenuTime = document.getElementById("MenuTime");
var ShowPackTime = document.getElementById("PackTime");
var ShowPackAvgSeconds = document.getElementById("PackerSeconds");
var ShowPackAvgMinutes = document.getElementById("PackerMinutes");
var ShowMenuAvgSeconds = document.getElementById("MenuMinutes");
var ShowMenuAvgMinutes = document.getElementById("MenuSeconds");
var DivisionSeconds = 60;
var TotalTime = 0;
var MenuTime = 0;
var PackTime = 0;
var AllMenuTimes = 0;
var AllPackTimes = 0;
var TotalMenuOrders = 0;
var TotalPackOrders = 0;
var MenuOrdersTotalSeconds = 0;
var PackOrdersTotalSeconds = 0;
var MenuAvgMinutes = 0;
var MenuAvgSeconds = 0;
var PackAvgSeconds = 0;
var PackAvgMinutes = 0;
StartButton.onclick = function(){
TotalMenuOrders + 1;
MenuTime = 0;
ShowMenuTime.innerHTML = MenuTime;
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
window.alert ("I work");
}
//This starts the timer. Inverval is a variable that holds the timer number.
function startTimer () {
StopwatchSeconds++;
TotalTime++;
MenuTime++;
AllMenuTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes; // Makes this a string in html
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
// When the start button is pressed this function starts. it adds 1 to
Stopwatch, total and Menu every 1000 increments that Interval hits.
// This also says if StopwatchSeconds goes above 59 itll reset to 0 and if
its below itll keep counting.
TillOpenButton.onclick = function () {
PackTime = 0;
ShowPackTime.innerHTML = PackTime;
ShowMenuTime.innerHTML = MenuTime;
PackInterval = setInterval(startPackerTimer, 1000);
Interval+PackInterval;
clearInterval(Interval);
/* if (TotalMenuOrders < 1) {
AllMenuTimes / TotalMenuOrders = MenuOrdersTotalSeconds;
MenuOrderTotalSeconds % 60 = MenuAvgSeconds;
MenuAvgMinutes = Math.floor(MenuOrderTotalSeconds/60);
ShowMenuAvgMinutes.innerHTML = MenuAvgMinutes;
ShowMenuAvgSeconds.innerHTML = MenuAvgSeconds;
}
*/
}
// When this button is pressed it stops the first timer and the menu timer.
It then starts a new timer and function which add to the variable that will
show the total time.
// It does clear the variable Interval though
FinishButton.onclick = function (){
clearInterval(Interval);
ShowPackTime.innerHTML = PackTime;
clearInterval(PackInterval);
StopwatchSeconds = 0;
StopwatchMinutes = 0;
ShowSeconds.innerHTMl = 0 + StopwatchSeconds;
ShowMinutes.innerHTML = 0 + StopwatchMinutes;
AllPackTimes += PackTime;
TotalPackOrders++;
/*AllPackTimes/TotalPackOrders = PackOrderTotalSeconds;
PackOrderTotalSeconds % DivisionSeconds = PackAvgSeconds;
PackAvgMinutes = Math.floor(PackOrderTotalSeconds/60);
ShowPackAvgMinutes.innerHTML = PackAvgMinutes;
ShowPackAvgSeconds.innerHTML = PackAvgSeconds;*/
}
// When the Finish Button is pressed it clears everything. Resets
everything. except Menu Time, Total Time and PackTime. I need 3 new
variables to hold these to get the average.
function startPackerTimer () {
StopwatchSeconds++;
TotalTime++;
PackTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
// Same deal but with the Till open button. Still adds onto
STopwatchSeconds so the variable doesn't change.
}
New solution, wich allows to create different timers and keep track of them:
//a method to setup a new timer
function Timer(Name){
this.timeElement=document.createElement("div");
(this.stopButton=document.createElement("button")).innerHTML="STOP";
(this.startButton=document.createElement("button")).innerHTML="START";
(this.Name=document.createElement("h1")).innerHTML=Name;
[this.Name,this.timeElement,this.startButton,this.stopButton].forEach(el=>document.body.appendChild(el));
this.stopButton.addEventListener("click",this.stop.bind(this));
this.startButton.addEventListener("click",this.start.bind(this));
this.seconds=0;
this.minutes=0;
}
Timer.prototype={
update:function() {
this.seconds++;
if(this.seconds > 59) {
this.seconds=0;
this.minutes++;
}
var secTemp="00"+this.seconds, minTemp="00"+this.minutes;
this.timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
},
stop:function(){
if(this.interval) clearInterval(this.interval);
this.running=false;
if(this.onstop) this.onstop(this);
}
start:function(){
if(this.interval) clearInterval(this.interval);
this.interval = setInterval(this.update.bind(this), 1000);
this.running=true;
if(this.onstart) this.onstart(this);
}
};
This implements a Timer with OOP. So you can create multiple timers, and they wont influence each other.
You can create a timer like this:
var timer= new Timer("The Name");
You can also change events, set/read the times and check if running:
timer.start();//start the timer ( can also be done with the ui button)
timer.stop();
timer.onstart=()=>alert("Started!");
timer.onstop=()=>alert("Stopped!");
console.log(timer.running,timer.minutes,timer.seconds);
If you want to wait for multiple timers and to calculate the average if all of them stopped:
var timers=["Timer 1", "Timer 2"].map(name=>new Timer(name));//create two timers and store in array
timers.forEach(function(timer){
timer.running=true;
timer.onstop=function(){
if(timers.some(t=>t.running)) return;//if theres a running timer dont procceed
var seconds=timers.reduce((seconds,timer)=>seconds+=(timer.seconds+timer.minutes*60),0);
var average=seconds/timers.length;
alert("Average: "+average+"s");
};
});
http://jsbin.com/coduvohewu/edit?output
The old solution, adding a timer if the new button is pressed, and stops the old one then:
So you want to stop the current timer, and create a new one below that? Maybe you could refactor the code a bit, doing sth like this:
window.onload = function () {
var seconds= 0,minutes = 0;
var times=[];
var Interval;
var timeElement;
//a method to setup a new timer
function createTimer(dontsave){
if(times.length>3) return alert(times.map(el=>el.join(":")).join());
timeElement=document.createElement("div");
document.body.appendChild(timeElement);
if(!dontsave) times.push([minutes,seconds]);
}
createTimer(true);
//a method to let the timer run
function startTimer () {
seconds++;
if(seconds > 59) {
seconds=0;
minutes++;
}
var secTemp="00"+seconds,minTemp="00"+minutes;
timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
}
//assign to buttons:
document.getElementById("ButtonStart").onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
document.getElementById("ButtonNew").onclick=createTimer;
};
http://jsbin.com/mujisaweyo/edit?output
This simply creates a new div in the DOM if you press a button with the id ButtonNew . So the current time stays as a text in the old Element, and it keeps counting in the new one. Ive also added a zero filling...

How to change the speed of setInterval in real time

I would like to know how to change the speed of setInterval in real time e.g:
if (score < 10)
repeater = setInterval(function() {
spawnEnemy();
}, 1000);
if (score => 10)
repeater = setInterval(function() {
spawnEnemy();
}, 500);
I know this method doesn't work, but is there a way that I can achieve this some other way?
jsFiddle Demo
There is no way to change the interval speed itself once running. The only way to do it is to have a variable for the speed, and then clear the interval and start a new one with the new speed.
var speed = 500;
var changeSpeed = speed;
repeater = setInterval(repeaterFn, speed);
function repeaterFn(){
spawnEnemy();
if( changeSpeed != speed ){
clearInterval(repeater);
speed = changeSpeed;
repeater = setInterval(repeaterFn, speed);
}
}
function changeRepeater(){
changeSpeed = 700;
}
Another way would be to just use setTimeout rather than setInterval. Do the check every time so you can keep your speed logic in a seperate function.
var game_over = false;
var score = 0;
function getSpeedFromScore(score)
{
if (score > 20) {
game_over = true;
}
if (score < 10) {
return 1000;
} else {
return 500;
}
}
function spawnEnemyThenWait() {
if (!game_over) {
spawnEnemy();
var speed = getSpeedFromScore(score);
setTimeout(spawnEnemyThenWait, speed);
}
}
JS Fiddle http://jsfiddle.net/bq926xz6/
You can use clearInterval:
if (score < 10) {
clearInterval(repeater);
repeater = setInterval(spawnEnemy, 1000);
}
if (score => 10) {
clearInterval(repeater);
repeater = setInterval(spawnEnemy, 500);
}
But it depends on the context. If this snippet is executed more often, than it has to be, you will need some kind of mechanism to prevent it from resetting your interval all the time.
But there is (as I wrote in the comment to the question) no way to use clearInterval and change the interval itself. At least not without replacing it by a new interval as shown above.
You can use a game loop and track the spawn state in an enemy class:
// press f12 so see console
function Enemy() {
this.spawned = false;
this.spawnOn = 20;
this.tick = function () {
this.spawnOn = this.spawnOn - 1;
if (this.spawnOn == 0) {
this.spawned = true;
}
}
this.goBackToYourCage = function () {
this.spawnOn = Math.floor(Math.random() * 50) + 1;
this.spawned = false;
}
}
var enemy = new Enemy();
window.setInterval(function () {
enemy.tick();
if (enemy.spawned) {
console.log('spawned');
enemy.goBackToYourCage();
console.log('Next spawin in :' + enemy.spawnOn);
}
}, 100);
http://jsfiddle.net/martijn/qxt2fe8y/2/

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

Categories