Incrementing page number with JavaScript - javascript

I tried to figure out why the following code doesn't increment the page number, excepting from 1 to 2, but I couldn't find out.
<script>
var n = 1;
function increment() {
return ++n;
}
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "Timp rămas: "+secs+" secunde.";
if(secs < 1) {
clearTimeout(timer);
window.location.replace('question.php?n='+increment(n));
element.innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
Ideas?

Try this:
var params = new URL(document.location).searchParams;
var n = params ? params.get('n') || 1 : 1;
So n is read from URL and not set to 1 everytime a page is loaded.
Edit: ah, and maybe:
var timer = setTimeout(function(){countDown(secs, elem);},1000);

Related

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...

Countdown parameter with Javascript function

I want to create a js function , that counts down to 0 from a parameter s.
and displays that at a <p> with the id = count , the function starts via onclick="countdown(60)" from a Button , but somehow it doesn t work.
Someone has a idea why ?
Thank you for your help.
var count ;
function countdown(s){
count = s ;
while (s > 0) {
document.getElementById("count").innerText = count ;
setTimeout(tick(), 1000) ;
}
document.getElementById("count").innerText = "ready" ;
}
function tick (){
count -- ;
}
Few points:
Your while loop will stack the setInterval calls immediately, and therefore they'll all fire after 1 second.
Calling setTimeout(tick().. will execute the tick function immediately
See the below as an alternative:
var countdown = function(s){
var c = document.getElementById("count");
var tick = function(){
c.innerText = s;
};
var ready = function(){
clearInterval(i);
c.innerText = "ready";
};
tick();
var i = setInterval(function(){
(s>0) ? function(){ s--;tick(); }() : ready();
}, 1000);
}
countdown(10);
<div id="count"></div>
Try this:
var count;
function countdown(s){
s = count; // reverse this line and it should work
while (s > 0) {
document.getElementById("count").innerText = count ;
setTimeout(tick(), 1000);
}
document.getElementById("count").innerText = "ready" ;
}
function tick (){
count -- ;
}

setInterval won't get out of loop

The following javascript code takes randomly selected value from a array and types it in the input box. I've used jquery. I want to end setInterval "zaman2", so after It ends I can retype the next random string to the input box. But the loop doesn't end and gets stuck. How can I solve this?
Link to jsFiddle: http://jsfiddle.net/AQbq4/4/
var dersler = [...very long list...];
var zaman = setTimeout(function() {
var yeniDers = dersler[Math.floor(Math.random()*dersler.length)];
sayac = 0;
var zaman2 = setInterval(function() {
var harf = yeniDers.slice(0,(sayac+1));
sayac++;
$('#main-search').attr('placeholder', harf).typeahead({source: dersler});
if (sayac == yeniDers.length) {
clearInterval(zaman2);
}
},450);
},2000);
Don't you mean
DEMO
var tId, tId2;
function show() {
var ran = arr[Math.floor(Math.random()*arr.length)];
cnt = 0;
tId = setInterval(function() {
var char = ran.slice(0,(cnt+1));
cnt++;
$( '#main-search' ).attr('placeholder', char);
if (cnt == ran.length) {
clearInterval(tId);
tId2=setTimeout(show,2000);
}
},450);
}
show();

javascript array cycling only first var

I am using javascript to cycle through an array of urls within an iframe and so far when the prev or next buttons are pressed it jumps to the first var in the array and both prev and next functions end. Any ideas?
<iframe id="myFrame" src="http://startpage.com" width="484px" height = "424px"></iframe>
<button onclick = "prevPage(); ">Prev</button>
<button onclick = "nextPage(); ">Next</button>
<script>
var sites=new Array();
sites[0]="http://site1.html";
sites[1]="http://site2.html";
sites[2]="http://site3.html";
sites[3]="http://site4.html";
function nextPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 4 ,number.length-3);
number = parseInt(number) + 1;
document.getElementById("myFrame").src=sites[0];
}
function prevPage() {
var number = document.getElementById("myFrame").src;
number = number.substring(number.length - 3 ,number.length-4);
number = parseInt(number) - 1;
document.getElementById("myFrame").src=sites[0];
}
</script>
Why are you using the URL as your 'position' storage? It'd be FAR easier to just use a variable:
var curPos = 0;
function nextPage() {
curPos++;
if (curPos >= sites.length) {
curPos = 0;
}
document.getElementById('myframe').src = sites[curPos];
}
function prevPage() {
curPos--;
if (curPos < 0) {
curPos = sites.length - 1;
}
document.getElementById('myframe'.).src = sites[curPos];
}
If I understood your problem correctly I think all you need to do is use document.getElementById("myFrame").src=sites[number]; instead of document.getElementById("myFrame").src=sites[0];
May be
document.getElementById("myFrame").src=sites[number-1];
is what you are trying to do in both functions.

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