Dynamically create multiple slide shows using setTimeout - javascript

I want to create a slide show of the number of objects in the "SliderArray" array when I click on the button.
The current JSfiddle is available in standalone mode.
When I take the function into the loop, things get messy
var myFunction = function() {
if (counter == 0) {
$('#' + sliderarray[0].slaytarray[counter].id).fadeIn();
frametime = sliderarray[0].slaytarray[counter].frame_time * 1000;
counter++;
} else if (counter == sliderarray[0].slaytarray.length) {
$('#' + sliderarray[0].slaytarray[counter - 1].id).fadeOut();
counter = 0;
frametime = 0;
} else {
$('#' + sliderarray[0].slaytarray[counter - 1].id).fadeOut();
$('#' + sliderarray[0].slaytarray[counter].id).fadeIn();
frametime = sliderarray[0].slaytarray[counter].frame_time * 1000;
counter++;
}
timeout = setTimeout(myFunction, frametime);
}
var timeout = setTimeout(myFunction, frametime);
And here my objects

This is "messy" because you never manipulate the second slider.
I fixed it by using a .forEach on the sliderarray:
var myFunction = function() {
if (counter == 0) {
sliderarray.forEach(function (slider) {
$('#' + slider.slaytarray[counter].id).fadeIn();
frametime = slider.slaytarray[counter].frame_time * 1000;
});
counter++;
} else if (counter == sliderarray[0].slaytarray.length) {
sliderarray.forEach(function (slider) {
$('#' + slider.slaytarray[counter - 1].id).fadeOut();
});
counter = 0;
frametime = 0;
} else {
sliderarray.forEach(function (slider) {
$('#' + slider.slaytarray[counter - 1].id).fadeOut();
$('#' + slider.slaytarray[counter].id).fadeIn();
frametime = slider.slaytarray[counter].frame_time * 1000;
});
counter++;
}
There is still a problem for the frametime because you're only using once when two are needed. I'll just let you look into it.
See updated JSFiddle

Related

How do I get my timer to stop, when my 10th and last question has been answered?

The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz

multiple stopwatch in jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to make multiples stopwatches in jquery, but the problem is i want the stopwatch the respective stopwatch to sun when we hit the corresponding button, and should stop when we hit button for another stopwatch and that respective stopwatch should start simultaneously, please see the image for reference, i know the question is not so clear, sorry for inconvenience.
thanks in advance.
try this one:
$(document).ready(function() {
(function($){
$.extend({
APP : {
formatTimer : function(a) {
if (a < 10) {
a = '0' + a;
}
return a;
},
startTimer : function(dir) {
var a;
// save type
$.APP.dir = dir;
// get current date
$.APP.d1 = new Date();
switch($.APP.state) {
case 'pause' :
// resume timer
// get current timestamp (for calculations) and
// substract time difference between pause and now
$.APP.t1 = $.APP.d1.getTime() - $.APP.td;
break;
default :
// get current timestamp (for calculations)
$.APP.t1 = $.APP.d1.getTime();
// if countdown add ms based on seconds in textfield
if ($.APP.dir === 'cd') {
$.APP.t1 += parseInt($('#cd_seconds').val())*1000;
}
break;
}
// reset state
$.APP.state = 'alive';
$('#' + $.APP.dir + '_status').html('Running');
// start loop
$.APP.loopTimer();
},
pauseTimer : function() {
// save timestamp of pause
$.APP.dp = new Date();
$.APP.tp = $.APP.dp.getTime();
// save elapsed time (until pause)
$.APP.td = $.APP.tp - $.APP.t1;
// change button value
$('#' + $.APP.dir + '_start').val('Resume');
// set state
$.APP.state = 'pause';
$('#' + $.APP.dir + '_status').html('Paused');
},
stopTimer : function() {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'stop';
$('#' + $.APP.dir + '_status').html('Stopped');
},
resetTimer : function() {
// reset display
$('#' + $.APP.dir + '_ms,#' + $.APP.dir + '_s,#' + $.APP.dir + '_m,#' + $.APP.dir + '_h').html('00');
// change button value
$('#' + $.APP.dir + '_start').val('Start');
// set state
$.APP.state = 'reset';
$('#' + $.APP.dir + '_status').html('Reset & Idle again');
},
endTimer : function(callback) {
// change button value
$('#' + $.APP.dir + '_start').val('Restart');
// set state
$.APP.state = 'end';
// invoke callback
if (typeof callback === 'function') {
callback();
}
},
loopTimer : function() {
var td;
var d2,t2;
var ms = 0;
var s = 0;
var m = 0;
var h = 0;
if ($.APP.state === 'alive') {
// get current date and convert it into
// timestamp for calculations
d2 = new Date();
t2 = d2.getTime();
// calculate time difference between
// initial and current timestamp
if ($.APP.dir === 'sw') {
td = t2 - $.APP.t1;
// reversed if countdown
} else {
td = $.APP.t1 - t2;
if (td <= 0) {
// if time difference is 0 end countdown
$.APP.endTimer(function(){
$.APP.resetTimer();
$('#' + $.APP.dir + '_status').html('Ended & Reset');
});
}
}
// calculate milliseconds
ms = td%1000;
if (ms < 1) {
ms = 0;
} else {
// calculate seconds
s = (td-ms)/1000;
if (s < 1) {
s = 0;
} else {
// calculate minutes
var m = (s-(s%60))/60;
if (m < 1) {
m = 0;
} else {
// calculate hours
var h = (m-(m%60))/60;
if (h < 1) {
h = 0;
}
}
}
}
// substract elapsed minutes & hours
ms = Math.round(ms/100);
s = s-(m*60);
m = m-(h*60);
// update display
$('#' + $.APP.dir + '_ms').html($.APP.formatTimer(ms));
$('#' + $.APP.dir + '_s').html($.APP.formatTimer(s));
$('#' + $.APP.dir + '_m').html($.APP.formatTimer(m));
$('#' + $.APP.dir + '_h').html($.APP.formatTimer(h));
// loop
$.APP.t = setTimeout($.APP.loopTimer,1);
} else {
// kill loop
clearTimeout($.APP.t);
return true;
}
}
}
});
$('#sw_start').live('click', function() {
$.APP.startTimer('sw');
});
$('#cd_start').live('click', function() {
$.APP.startTimer('cd');
});
$('#sw_stop,#cd_stop').live('click', function() {
$.APP.stopTimer();
});
$('#sw_reset,#cd_reset').live('click', function() {
$.APP.resetTimer();
});
$('#sw_pause,#cd_pause').live('click', function() {
$.APP.pauseTimer();
});
})(jQuery);
});
DEMO HERE
OR
$(function () {
// Never assume one widget is just used once in the page. You might
// think of adding a second one. So, we adjust accordingly.
$('.stopwatch').each(function () {
// Cache very important elements, especially the ones used always
var element = $(this);
var running = element.data('autostart');
var hoursElement = element.find('.hours');
var minutesElement = element.find('.minutes');
var secondsElement = element.find('.seconds');
var millisecondsElement = element.find('.milliseconds');
var toggleElement = element.find('.toggle');
var resetElement = element.find('.reset');
var pauseText = toggleElement.data('pausetext');
var resumeText = toggleElement.data('resumetext');
var startText = toggleElement.text();
// And it's better to keep the state of time in variables
// than parsing them from the html.
var hours, minutes, seconds, milliseconds, timer;
function prependZero(time, length) {
// Quick way to turn number to string is to prepend it with a string
// Also, a quick way to turn floats to integers is to complement with 0
time = '' + (time | 0);
// And strings have length too. Prepend 0 until right.
while (time.length < length) time = '0' + time;
return time;
}
function setStopwatch(hours, minutes, seconds, milliseconds) {
// Using text(). html() will construct HTML when it finds one, overhead.
hoursElement.text(prependZero(hours, 2));
minutesElement.text(prependZero(minutes, 2));
secondsElement.text(prependZero(seconds, 2));
millisecondsElement.text(prependZero(milliseconds, 3));
}
// Update time in stopwatch periodically - every 25ms
function runTimer() {
// Using ES5 Date.now() to get current timestamp
var startTime = Date.now();
var prevHours = hours;
var prevMinutes = minutes;
var prevSeconds = seconds;
var prevMilliseconds = milliseconds;
timer = setInterval(function () {
var timeElapsed = Date.now() - startTime;
hours = (timeElapsed / 3600000) + prevHours;
minutes = ((timeElapsed / 60000) + prevMinutes) % 60;
seconds = ((timeElapsed / 1000) + prevSeconds) % 60;
milliseconds = (timeElapsed + prevMilliseconds) % 1000;
setStopwatch(hours, minutes, seconds, milliseconds);
}, 25);
}
// Split out timer functions into functions.
// Easier to read and write down responsibilities
function run() {
running = true;
runTimer();
toggleElement.text(pauseText);
}
function pause() {
running = false;
clearTimeout(timer);
toggleElement.text(resumeText);
}
function reset() {
running = false;
pause();
hours = minutes = seconds = milliseconds = 0;
setStopwatch(hours, minutes, seconds, milliseconds);
toggleElement.text(startText);
}
// And button handlers merely call out the responsibilities
toggleElement.on('click', function () {
(running) ? pause() : run();
});
resetElement.on('click', function () {
reset();
});
// Another advantageous thing about factoring out functions is that
// They are reusable, callable elsewhere.
reset();
if(running) run();
});
});
DEMO HERE

Stop and run again timer via pure javascript

I want to make a simple countdown timer which can be set by + or - and also it can be stopped and run by clicking on itself.
My problem is when it is stopped and then runs it shows NAN for the first number.
I suppose it is because of setTimer function but I don't know how to fix that.Here is my code:
var x = document.getElementsByClassName('session');
var seconds = 60;
var session;
var t;
var on = true;
var minutes = 1;
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = minutes;
}
function increase() {
minutes++;
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = minutes;
}
}
function decrease() {
minutes--;
for (var i = 0; i < x.length; i++) {
if (x[i].innerHTML > 0) {
x[i].innerHTML = minutes;
}
}
}
function setSession() {
session = x[1].innerHTML - 1;
}
function timer() {
if (seconds > 0) {
seconds--;
if (seconds == 0 && session > 0) {
session--;
seconds = 60;
}
}
x[1].innerHTML = session + ':' + seconds;
}
function stoptimer() {
clearInterval(t);
}
function general() {
if (on) {
on = false;
t = setInterval(timer, 100);
} else {
on = true;
stoptimer();
}
}
<div class='session'></div>
<div id='increase' onclick='decrease()'>-</div>
<div id='increase' onclick='increase()'>+</div>
<div class='session' onclick='setSession();general()'></div>
You shouldn't be setting session from the html entity. Basically this creates issues with parsing and could potentially break your code. Also, you subtract one every time you get this value, throwing a spanner in the works.
I re-shuffled your code a bit and added some notes, take a look:
var x = document.getElementsByClassName('session');
var seconds = 0;
var session;
var timer; // give this a useful name
var timerRunning = false; // give this a useful name
var minutes = 1;
function updateMinutes(newMinutes){
if (timerRunning){
return; // do not allow updating of countdown while count down is running
}
if(newMinutes !== undefined){ // allow this function to be called without any parameters
minutes = newMinutes;
}
if(minutes < 1){
minutes = 1; //set your minimum allowed value
}
if(minutes > 99999){
minutes = 99999; //could also have some sort of maximum;
}
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = minutes;
}
session = minutes; // now this can only be set while timer is not running, so no need to get it from the html
//also, i would let this start at the exact same value as minutes, and have seconds start at zero
}
updateMinutes(); // call this now to initialise the display
function increase() {
updateMinutes(minutes + 1);
}
function decrease() {
updateMinutes(minutes - 1);
}
function timer_tick() {
if (seconds > 0) {
seconds--;
if (seconds == -1 && session > 0) { //because of where you've positioned your logic, this should check for negative one, no zero, otherwise you'll never display a zero seconds value
session--;
seconds = 59; //when a timer clocks over it goes to 59
}
}
if (session > 0 || seconds > 0){
x[1].innerHTML = session + ':' + seconds;
}
else{// you need to detect the ending
x[1].innerHTML = "Finished!!";
}
}
function timer_stop() {
clearInterval(timer);
}
function timer_start(){
timer = setInterval(timer_tick, 1000);
}
function timer_toggle() { //give these timer functions consistent names
if (!timerRunning) {
timer_start();
} else {
timer_stop();
}
timerRunning = !timerRunning; //just flip the boolean
}
You set
x[1].innerHTML = session + ':' + seconds;
and then try to calculate that as
session = x[1].innerHTML - 1;
You need to either put the session:seconds in another place or do
session = parseInt(x[1].innerHTML,10) - 1;
Ok, I would propose another approach. Use a class for your timer, like this:
function MyTimer(htmlEl) {
this.sec = 0;
this.min = 0;
this.elt = htmlEl;
}
MyTimer.prototype.set = function(m) {
this.min = m;
this.display();
var self = this;
this._dec = function() {
self.sec--;
if (self.sec < 0) {
if (self.min == 0) {
self.stop();
} else {
self.min -= 1;
self.sec = 59;
}
}
self.display();
}
}
MyTimer.prototype.display = function() {
this.elt.innerHTML = this.min + ":" + this.sec;
}
MyTimer.prototype.toggle = function() {
if (this.interval) {
this.stop();
this.interval = undefined;
} else this.start();
}
MyTimer.prototype.start = function() {
this.interval = setInterval(this._dec, 100);
};
MyTimer.prototype.stop = function() {
clearInterval(this.interval);
};
Then, you can use it like this:
window.onload = init;
var minutes, x, timer;
function init() {
x = document.getElementsByClassName('session');
timer = new MyTimer(x[1]);
minutes = 0;
}
function increase() {
minutes += 1;
x[0].innerHTML = minutes;
timer.set(minutes);
}
function decrease() {
minutes -= 1;
x[0].innerHTML = minutes;
timer.set(minutes);
}
function general() {
timer.toggle();
}
The only change in your html is to remove the setSession call:
<div id='timer' onclick='general()'></div>
This code is more clear. You encapsulate the logic and the min/sec in an object, which is reusable. Here is a working fiddle : https://jsfiddle.net/Shitsu/zs7osc59/.
The origin of your problem is in the code
session = x[1].innerHTML - 1;
Let's re-visit the purpose of keeping of the variable 'session'. I guess it is to keep the value of the maximum value, the upper limit of the minutes, from where to start counting, right? On the other hand, the 'minutes' variable is to keep the temporary value of the minutes. What confused you here is that you've used 'minutes' in place of it's upper limit (what actually is the session's role), in this code for example
function increase() {
minutes++;
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = minutes;
}
}
see, you are updating html by the value of 'minutes', and later you are reading that value into 'session' by that evil code:
session = x[1].innerHTML - 1;
So, why? Why you need to update the value of 'your' variable from html? You should only update the html according to the value of session var and not vice versa. Let's go on and make life simpler...
Let's keep the temporary value of minutes in 'minutes', let's also keep the upper limit in a variable session and, please, let's rename it to maxMinutes. Let's update the 'maxMinutes' only when user clicks '+' or '-' (NEVER from html).
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<script>
var x = document.getElementsByClassName('session');
var maxMinutes = 0;
var minutes = maxMinutes;
var seconds = 0;
var timer;
var on = false;
function increase() {
if(on) {
return;
}
maxMinutes++;
minutes = maxMinutes;
x[0].innerHTML = maxMinutes;
x[1].innerHTML = minutes;
}
function decrease() {
if(on) {
return;
}
if(maxMinutes == 0)
{
return;
}
maxMinutes--;
minutes=maxMinutes;
x[0].innerHTML = maxMinutes;
x[1].innerHTML = minutes;
}
function periodicRun() {
if (seconds > 0) {
seconds--;
}
else if(seconds == 0)
{
if(minutes > 0) {
minutes--;
seconds = 60;
}
else
{
stopTimer(timer);
return;
}
}
x[1].innerHTML = minutes + ':' + seconds;
}
function stoptimer() {
clearInterval(timer);
}
function general() {
if (on) {
on = false;
stoptimer();
} else {
on = true;
timer = setInterval(periodicRun, 500);
}
}
$(document).ready(function(){
increase();
});
</script>
<div class='session'></div>
<div id='increase' onclick='decrease()'>-</div>
<div id='increase' onclick='increase()'>+</div>
<div class='session' onclick='general()'></div>
</body>
</html>
Note, that the only place where the maxLimits get's assigned a value is in increase() and decrease(). The 'minutes' and html are in their turn being updated according to maxMinutes.
Good Luck!

Using setInterval in a loop to change interval

I am using the technique in the second answer here:
Changing the interval of SetInterval while it's running
but the change in the interval is not being set. Code is also using OpenLayers 3:
var coordinate,
i = 1,
length = multipointCoords[0].length;
var currentTime = tracksTime[0];
var nextTime = tracksTime[1];
speedOption = 100; // the highter this value, the faster the tracks, see next line
var transitionTime = (nextTime - currentTime) / speedOption;
var timer;
timer = setInterval(function() {
segmentConstruction(multipointCoords, tracksTime);
}, transitionTime);
function segmentConstruction(multipointCoords, tracksTime) {
coordinate = ol.proj.fromLonLat(multipointCoords[0][i]);
lineString.appendCoordinate(coordinate);
if (i === length - 1) {
clearInterval(timer);
} else {
i++;
map.addLayer(trackLayer);
clearInterval(timer);
currentTime = tracksTime[i];
nextTime = tracksTime[i + 1];
timer = setInterval(function() {
segmentConstruction(multipointCoords);
}, transitionTime);
};
};
What am I doing wrong?
Thanks.
var currentTime = tracksTime[0];
var nextTime = tracksTime[1];
speedOption = 100; // the highter this value, the faster the tracks, see next line
var transitionTime = (nextTime - currentTime) / speedOption;
You calculate transitionTime here.
if (i === length - 1) {
clearInterval(timer);
} else {
i++;
map.addLayer(trackLayer);
clearInterval(timer);
currentTime = tracksTime[i];//<------------------|
nextTime = tracksTime[i + 1];//<-----------------|
timer = setInterval(function() {// |
segmentConstruction(multipointCoords);// |
}, transitionTime);// <----------------------------->Not redefined
};
Here you use the same transitionTime as above it is not redifined !
Why not, It's not an error, but ...
I don't think your issue come from the timer, but from the param's you have.
Here a snippet to see that your code concerning timing and interval have no problem :
I just removed everything not concerned by 'timing' and interval.
var log = function(val){
console.log(val);
document.getElementById('el').innerHTML+='<div><pre>' + val + '</pre><div>';
}
var timer ,
i = 1 ,
length = 5 ,
transitionTime = 200 ;
timer = setInterval(function() {
log('first timerId : ' + timer);
segmentConstruction()
}, transitionTime );
function segmentConstruction(multipointCoords, tracksTime) {
log(' \tsegmentConstruction : i = ' + i + ' / ' + length);
//if (i === length - 1) {
if (i >= length - 1) {
clearInterval(timer);
log('\t\twe finish with : i = ' + i + ' / ' + length);
} else {
i++;
clearInterval(timer);
timer = setInterval(function() {
log('loop timerId : ' + timer);
segmentConstruction();
}, transitionTime);
};
};
<div id='el'></div>

pause and continue using setInterval

what i want to achieve is when you click this href pause/continue the timer pauses and continues when pressed again.
<script>
$(document).ready(function () {
var counter = 10;
var id = setInterval(function() {
counter--;
if(counter > 0) {
var msg = 'You can continue ' + counter + ' seconds';
$('#notice').text(msg);
} else {
$('#notice').hide();
$('#download').show();
clearInterval(id);
}
}, 1000);
});
</script>
My HTML in relevance to the jQuery is here if you need.
Continue !!<p id="notice">
You can continue in 10 seconds</p>
Well, I would just have your pause event set a boolean, and then check that boolean before you decrement your counter:
pause/continue
and
var ispaused=false;
function setPause(){
ispaused=!ispaused;
}
and
$(document).ready(function () {
var counter = 10;
var id = setInterval(function() {
if(!ispaused){ ////the only new line I added from your example above
counter--;
if(counter > 0) {
var msg = 'You can continue ' + counter + ' seconds';
$('#notice').text(msg);
} else {
$('#notice').hide();
$('#download').show();
clearInterval(id);
}
}
}, 1000);
});
That should do it, right?

Categories

Resources