Break while loop with timer? - javascript

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);

Related

clearInterval and set it again after x seconds

I want to do simple interval with with if, It is checking a variable's value and doing a function again().
again function contains clearInterval, i++ and setTimeout to call interval again after x seconds
var speed = 1000;
var wait = 0;
var i = 0;
function init() {
setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(init());
i++;
setTimeout(function() {
setInterval(init(), speed);
}, time);
}
init();
I expect output like this:
1, 2, 3, Waiting x sec's , 5, 1, 2, ...
but code is doing some thing crazy, Its going faster and faster. I don't know why.
Here's a codepen with example (can crash your browser!)
Can you fix it and explain? Thanks
You are not clearing interval but use function inside clearInterval method. Method init which is used has no return statement so clearInterval gets undefined in attribute, so it is not clearing nothing.
Fixed code:
var speed = 1000;
var wait = 0;
var i = 0;
var interval=null;
function init() {
interval = setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(interval);
i++;
setTimeout(function() {
init()
}, time);
}
init();
Function setInterval returns interval id and function clearInterval in attribute should get id of interval which we want to stop, so I created interval variable to save id. I am using this variable in clearInterval.
This is a small example how changing the delay of a setInterval call.
(function iife() {
var timer = null,
counter = 0;
function task() {
counter += 1;
console.log(counter);
// condition: every four reps
if (counter % 4 === 0) {
console.log("changed speed to 4 seconds");
return start(4000);
}
// condition: every seven reps
if (counter % 7 === 0) {
console.log("changed speed to 2 seconds");
return start(2000);
}
}
function start(delay) {
clearInterval(timer);
console.log("runs every " + delay + " miliseconds");
timer = setInterval(task, delay);
}
start(1000);
}());

timer implementation in javascript

I had written following code for implementing a timer in JS. But the issue is, for the subsequent recursive calls, the method throws reference error for timeChkSplitTime. How does it happen as its being passed in settimeout().
Also, later I used the easy timer js lib for this. If possible, pls provide an idea to configure the timer for minutes and seconds alone.
function timeChkold(timeChkSplitTime) {
var min = timeChkSplitTime[0], sec = timeChkSplitTime[1];
if (!(timeChkSplitTime[0]==0 && splitTime[1]==0)) {
var strSec, strMin = "0"+min.toString();
if (sec < 10) strSec = "0"+ sec.toString();
else strSec = sec.toString();
$(".timer-btn time").html(strMin+":"+strSec);
timeChkSplitTime[0]=0;
if (sec > 0) timeChkSplitTime[1]--;
else timeChkSplitTime[1] = 59;
setTimeout( "timeChk(timeChkSplitTime);", 1000);
}
else {
var startBtn = $(".start-btn");
startBtn.html("Start");
startBtn.css( {
"border": "1px solid #56B68B",
"background": "#56B68B",
});
var startTime = "01:00";
$(".timer-btn time").html(startTime);
}
}
setTimeout( "timeChk(timeChkSplitTime);", 1000);
should be
setTimeout( timeChk(timeChkSplitTime), 1000);
Variables aren't parsed through strings, on the line with the code:
setTimeout( "timeChk(timeChkSplitTime);", 1000);
It's literally reading the parameter as the value as the text timeChkSplitTime and not the value of the variable timeChkSplitTime. Other than using a string use a function for setTimeout:
setTimeout( timeChk(timeChkSplitTime), 1000);
your code is a little bit of a spaghetti code. you should seperate your code logic from the view. split them into functions. and most importantly, using setTimeout is not efficient in this case.
var CountdownTimer = function(startTime) {
var timeInSeconds = this.stringToSeconds(startTime);
this.original = timeInSeconds;
this.time = timeInSeconds;
this.running = false;
}
CountdownTimer.prototype.start = function(callback) {
this.running = true;
this.interval = setInterval(function() {
if(this.time < 1) {
this.running = false;
clearInterval(this.interval);
} else {
this.time -= 1;
callback();
}
}.bind(this), 1000);
}
CountdownTimer.prototype.pause = function() {
if(this.running) {
this.running = false;
clearInterval(this.interval);
}
}
CountdownTimer.prototype.restart = function() {
this.time = this.original;
}
CountdownTimer.prototype.stringToSeconds = function(timeSting) {
var timeArray = timeSting.split(':');
var minutes = parseInt(timeArray[0], 10);
var seconds = parseInt(timeArray[1], 10);
var totalSeconds = (minutes*60) + seconds;
return totalSeconds;
}
CountdownTimer.prototype.secondsToStrings = function(timeNumber) {
finalString = '';
var minutes = parseInt(timeNumber/60, 10);
var seconds = timeNumber - (minutes*60);
var minStr = String(minutes);
var secStr = String(seconds);
if(minutes < 10) minStr = "0" + minStr;
if(seconds < 10) secStr = "0" + secStr;
return minStr + ":" + secStr;
}
to run this code you can add the following
var countdownTest = new CountdownTimer("01:15");
countdownTest.start(onEachTick);
function onEachTick() {
var time = countdownTest.secondsToStrings(countdownTest.time);
console.log(time)
}
you can write your custom code in the onEachTick funciton.
you can check if the timer is running by typing countdownTest.running.
you can also restart and pause the timer. now you can customize your views however you want.

Changer SetInterval Values After Interval

If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->
Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.
what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>
you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()

Return the value of a variable

Code:
var n = 360; // 6 min of waiting after blocked
function countDown() {
n--;
if (n > 0) {
setTimeout(countDown, 1000);
}
$("span#waitcount").html(document.createTextNode(n));
}
var count = 50; // Count of tokens when reached 0 block the page
var counter = document.getElementById('counter');
var clickDisabled = false;
$('.slotMachineButton').click(function() {
if (clickDisabled)
return;
setTimeout(function() {
count--;
counter.innerHTML = count;
if (count === 0) {
$.blockUI({message: '<h1>Thank you for Playing!!!<br>Please wait for 6 munites to be able to play again.</h1>'});
setTimeout(function() {
$.unblockUI({
onUnblock: function() {
alert('Game has been resumed!!!');
}
});
}, 10000);
setTimeout(countDown, 1000);
}
});
clickDisabled = true;
setTimeout(function() {
clickDisabled = false;
}, 3000);
}
Goal:
When the token count reaches 0 return it to original value to start again another count, because whenever the count reaches zero it goes -1 and keeps going.
When 6 min waiting is over start another waiting, I dont know if I got the code right for this part but please do check.
If you want to keep your code and you don't follow the suggestions in the the comments, then to this:
var n = 360, // 6 min of waiting after blocked
count = 50, // Count of tokens when reached 0 block the page
counter = document.getElementById('counter'),
clickDisabled = false;
function countDown(){
if(n > 0){
setTimeout(countDown, 1000);
} else {
n = 360;
clickDisabled = false
}
$("span#waitcount").html(document.createTextNode(n));
n--;
}
$('.slotMachineButton').click(function () {
if (clickDisabled) {
return;
}
setTimeout(function () {
counter.innerHTML = count;
if (count === 0) {
$.blockUI({ message: '<h1>Thank you for Playing!!!<br>Please wait or 6 munites to be able to play again.</h1>' });
setTimeout(function () {
$.unblockUI({
onUnblock: function () {
clickDisabled = true;
alert('Game has been resumed!!!');
setTimeout(countDown, 10);
}
});
}, 1000);
count = 50;
}
count--;
});
clickDisabled = true;
setTimeout(function () {
clickDisabled = false;
}, 100);
});
Bud you should realy look for a diffrent aproach. I changed the timer values for testing.

Infinite Loop in Page Redirection Function of JavaScript

I am now working on a piece of code of JavaScript which will be used to redirect a page with a shown counter. The problem is, when counter reaches 0, countDown() function gets in an infinite loop which causes the page to remain the same. And of course, I could not resolve the problem yet. Can anyone help?
You can see the problem here:
http://kibristaodtuvarmis.com/index.html
Code is shown below:
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function countDown()
{
if (time == 0)
{
window.location = page;
return(0);
}
else
{
time--;
gett("container").innerHTML = time;
}
}
function gett(id)
{
if(document.getElementById) return document.getElementById(id);
if(document.all) return document.all.id;
if(document.layers) return document.layers.id;
if(window.opera) return window.opera.id;
}
function init()
{
if(gett("container"))
{
setInterval(countDown, 1000);
gett("container").innerHTML = time;
}
else
{
setTimeout(init, 50);
}
}
document.onload = init();
EDIT:
I have done the below changes in countDown() function and problem is resolved:
var control = false;
function countDown()
{
if (time == 0 && control == false)
{
control = true;
window.location = page;
return(0);
}
else if (time > 0)
{
time--;
gett("container").innerHTML = time;
}
else
{
return(0);
}
}
I would do something like this:
var b = false;
if (time == 0 && b == false)
{
b = true;
window.location = page;
return(0);
}
Try this part of code for by replacing your complete javascript Code :
var time = 10;
var page = "http://blog.kibristaodtuvarmis.com";
function startCount() {
time = time - 1;
console.log(time);
document.getElementById("container").innerHTML = time;
startCounter();
}
function startCounter() {
if (time !== 0) {
setTimeout(function () {
startCount();
},1000);
} else {
location.href = page;
}
}
if (window.addEventListener) {
window.addEventListener("load", startCount, false);
} else if (el.attachEvent) {
window.attachEvent("load", startCount);
}
I tried it, It works.
Tell me your reply after testing.
Are you wanting it to stop at 0? Assign the setInterval to a var and then use clearInterval if 0
your setIinterval continues executing before change the window.location and then causes this loop because time is 0 and should launch window.location again
you should clear the interval
var IdInterval = setInterval(function () {
//.... code
}, 10000);
and after the first execution of countDown with time==0 then:
clearInterval(IdInterval);

Categories

Resources