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?
Related
I'm playing around with making a little game in JS.
There's a day counter that increments every seconds through setInterval().
I would like to access the incremented variable daycount from inside the main new_game() function to trigger game events based on days that have passed.
Would appreciate if someone could help or point me in the right direction.
var day = $('#time');
var daycount = 0;
$(document).ready(function () {
$('#start').click(function () {
new_game();
$(this).addClass('disabled').html('Started');
})
});
function time() {
setInterval(function () {
daycount++;
day.html('Day ' + daycount);
return daycount;
}, 1000);
}
function new_game() {
time();
if(daycount == 5){
alert('something');
}
}
You could pass a callback function to time()
You can not return inside the setTimeout callback as there is nothing to return to.
Also as it stands now you are only checking dayCount when the new_game() is initialized....not each time it changes in the interval timer
let daycount = 0,
day = $('#day');
function time(callback) {
setInterval(function() {
daycount++;
day.html('Day ' + daycount);
callback(daycount);
}, 1000);
}
function new_game() {
function checkCount(daycount) {
if (daycount == 5) {
console.log('Is 5');
} else {
console.log('Not 5');
}
}
time(checkCount);
}
new_game()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="day">
It should be daycount not count here day.html('Day ' + daycount);
var day = $('#time');
var daycount = 0;
$(document).ready(function () {
$('#start').click(function () {
new_game();
$(this).addClass('disabled').html('Started');
})
});
function time() {
setInterval(function () {
daycount++;
day.html('Day ' + daycount);
if(daycount == 5){
alert('something');
}
//return daycount;
}, 1000);
}
function new_game() {
console.log("new_game called ");
time();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time">...</div>
<div id="start">Click me </div>
In addition to the requested functionality:
clearInterval() is added to prevent setInterval() from counting continuously.
<input> is added so the user can set the end count.
Details commented in demo
Demo
var day = $('#time');
var daycount = 0;
$(document).ready(function() {
$('#start').on('click', function() {
/* Assign counter as the timer() function
|| running every second.
*/
var counter = setInterval(timer, 1000);
/* Define timer() function to display the
|| daycount increments as the value of
|| output#time
|| When daycount reaches the value of user
|| input of input#end, run the
|| stop() function
*/
function timer() {
daycount++;
day.val('Day ' + daycount);
if (daycount === Number($('#end').val())) {
stop();
}
}
/* Define stop() function
|| clearInterval of counter() function
|| thereby stopping the count from going 4eva
|| log the count
*/
function stop() {
clearInterval(counter);
console.log('Day ' + daycount);
}
$(this).addClass('disabled').html('STARTED');
});
});
button,
input,
output {
font: inherit
}
input {
width: 5ch
}
.disabled {
pointer-events: none
}
<input id='end' type='number' min='0' max='999'>
<button id='start'>START</button>
<output id='time'></output>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a submit function on a textbox with JavaScript. When the script fires, it checks a Kendo grid for a certain article and adds +1 to its quantity as well as opening the corresponding cell in editing mode. What I want to achieve is that on every submit the timer that starts grid.editCell() will reset its timer.
Currently, the event fires properly. However, the timer doesn't get reset, although the clearTimeout() does work if I just simply start the timer and then clear it right afterwards.
JavaScript:
$('#txtBarcode').submit(function (e) {
var grid = $("#PickListDetailGrid").data("kendoGrid");
var dataSource = $("#PickListDetailGrid").data("kendoGrid").dataSource;
var allData = grid.dataSource.data();
var code = this.value;
var notification = $("#notification").data("kendoNotification");
var timer = null;
clearTimeout(timer);
$.each(allData, function (index, item) {
if (item.ArticleID == code) {
clearTimeout(timer);
timer = null;
if (item.Quantity > item.PickedQuantity && item.PickedQuantity.toString().length < 4) {
var edit = function () {
if (item.PickedQuantity != item.Quantity && timer != null) {
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
} else {
//do nothing
}
}
item.PickedQuantity++;
item.dirty = true;
dataSource.sync();
if (item.PickedQuantity != item.Quantity) {
console.log("tik tok");
if (timer) {
clearTimeout(timer); //cancel the previous timer.
timer = null;
}
timer = setTimeout(edit, 3000);
} else {
clearTimeout(timer);
timer = null;
}
document.getElementById("txtBarcode").value = "";
} else {
if (item.PickedQuantity.toString().length > 4) {
notification.hide();
notification.show({
message: "Added item"
}, "upload-success");
} else {
notification.hide();
notification.show({
title: "Quantity Error",
message: "You already picked this item to the maximum"
}, "error");
document.getElementById("txtBarcode").value = "";
grid.select("tr:eq(" + (index) + ")");
grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")");
$('.focus :input').focus();
}
}
}
})
})
You can try delay function like this. The delay function should be outside of the each function.
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
delay(function() {
//do something
}, 3000);
The problem was that var timer = null; had to be outside of the submit function to be properly cleared and set to null before assigning a new setTimeout() to it.
I was wondering is it possible to break a while loop with a timer?
looked on the internet but could not find a solution for it.
while (true) {
alert('hi');
} if (timer < 0) {
timer?
document.write('Time is up!');
break;
}
Thank you.
You should use setTimeout for this.
var timer = 3;
setTimeout(excuteMethod, 1000);
function excuteMethod() {
alert(timer + ' call');
timer--;
if (timer >= 0) setTimeout(excuteMethod, 1000);
}
Demo : http://jsfiddle.net/kishoresahas/9s9z7adt/
I'm not sure if this is the correct approach, but it works,
(function() {
var delay = 30;
var date = new Date();
var timer = date.setTime(date.getTime() + delay);
var count = 0;
function validate() {
var now = new Date();
if (+now > timer)
return false;
else
return true;
}
while (true) {
count++;
console.log(count);
if (!validate()) {
console.log("Time expired");
break;
}
// Fail safe.
if (count > 50000) {
console.log("Count breached")
break;
}
}
})()
You can change control value in timer function and break the loop.
var control = true;
while(control)
{
...
}
setTimeout(function(){
control = false;
}, delay); //delay is miliseconds
Or based on counter
var control = true,
counter = 10;
while(control){
...
}
// you can handle as count down
// count down counter every 1000 miliseconds
// after 10(counter start value) seconds
// change control value to false to break while loop
// and clear interval
var counterInterval = setInterval(function(){
counter--;
if(counter == 0)
{
control = false;
clearInterval(counterInterval);
}
},1000);
I'm officially stuck. I can't seem to get the stopTimer() function to work properly. Any help would be greatly appreciated. Thanks!
http://jsfiddle.net/4Efbd/1/
var counter;
function stopTimer() {
window.clearInterval(counter);
$('#queryTimer').html('');
}
function startTimer() {
var count = 60;
var counter = setInterval(function () {
count = count - 1;
if (count <= 0) {
window.clearInterval(counter);
return;
}
$('#queryTimer').html('Requery in:' + count + ' Seconds.');
}, 1000);
}
$('#start').click(function () {
startTimer();
});
$('#stop').click(function () {
stopTimer();
});
var counter = setInterval(function () {
That says "create a new variable counter". This means that the existing variable never gets changed, so clearInterval doesn't have the right identifier to clear it. You want to use the existing variable:
counter = setInterval(function () {
I have a simple countdown using setinterval and I get the error that my functions are not defined. I am using the buttons to start and stop the intervals. Any ideas why this happens?
Javascript
function startCount() {
$(function() {
var count = 10;
countdown = setInterval(function() {
$("p.countdown").html(count + " seconds remaining!");
if (count === 0) {
window.location = 'http://google.com';
}
count--;
}, 1000);
});
}
function startStop() {
clearInterval(countdown);
}
html
<p class="countdown"></p>
<button onclick="startCount()">Start</button>
<button onclick="startStop()">Stop</button>
demo
http://jsfiddle.net/54uQz/1/
Declare your countdown variable outside the startCount() function so that it is visible to both functions. At the moment it only exists in the first, so clearing the timer does nothing.
CODE:
var countdown;
function startCount() {
var count = 10;
countdown = setInterval(function() {
$("p.countdown").html(count + " seconds remaining!");
if (count === 0) {
window.location = 'http://google.com';
}
count--;
}, 1000);
}
function startStop() {
clearInterval(countdown);
}
The Updated Fiddle Example!