Return the value of a variable - javascript

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.

Related

javascript function delay or set time out not working

i am trying to code the typed jquery functinality in javascript.I am almost there.HEre i need to add a delay after loading the word.like a few secons(lest say 4 sec) after each word loaded. How can i do it. In tried delay and set time out.It is not working for me or i am placing in wrong position. How can i set it.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
setInterval(function() {
var interval = setInterval(function() {
document.getElementById('p1').innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 >= arr[count].length) {
dir = false;
}
} else {
count2--;
if (count2 < 0) {
dir = true;
clearInterval(interval);
}
}
}, 100);
count++;
if (count == 6) count = 0;
}, 2500);
<div style="width=100%">
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>
Your implementation will have problems if you add “A very long string” in to the array.
I’ve modified your code, hope it will help.
var count = 0,
count2 = 0,
arr = ["SWOO", "EXCITE", "WOW", "AMAZE", "IMPRESS", "EDUICATE"],
dir = true;
var p1 = document.getElementById("p1");
// Turning the intervals to on or off.
var onOff = function(bool, func, time) {
if (bool === true) {
interval = setInterval(func, time);
} else {
clearInterval(interval);
}
};
var eraseCharacters = function() {
// How long we want to wait before typing.
var wait = 1000;
// How fast we want to erase.
var erasingSpeed = 100;
var erase = function() {
p1.innerHTML = arr[count].substring(0, count2);
count2--;
if (count2 < 0) {
dir = true;
// Stop erasing.
onOff(false);
count++;
if (count === 6) {
count = 0;
}
// Start typing.
setTimeout(startTyping, wait);
}
};
// Start erasing.
onOff(true, erase, erasingSpeed);
};
var startTyping = function() {
// How long we want to wait before erasing.
var wait = 4000;
// How fast we want to type.
var typingSpeed = 100;
var type = function() {
p1.innerHTML = arr[count].substring(0, count2);
if (dir) {
count2++;
if (count2 > arr[count].length) {
dir = false;
// Stop typing.
onOff(false);
// Start erasing.
setTimeout(eraseCharacters, wait);
}
}
};
// Start typing.
onOff(true, type, typingSpeed);
};
// Start typing after 2 seconds.
setTimeout(startTyping, 2000);
<div style="width=100%">
<!-- Maybe it should be class. -->
<span id="p1" className="p2 hero-text-animate"></span> <span>them with video</span>
</div>

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

Break while loop with timer?

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

How do I add a pause function to this pageChange timer?

Below in the code is an array of pages which is shuffled and then each of them is displayed in an iframe for a certain amount of time. I want to be able to start/stop the pageChange function using a button or a mouse click. Can anyone help me with this? Below is the working code, or check this fiddle: http://jsfiddle.net/xaa1qccm/ (Thanks to Nobe4)
var pages=[];
pages[0]="http://example.com/";
pages[1]="http://www.iana.org/domains/reserved";
pages[2]="http://en.wikipedia.org/wiki/Main_Page";
pages[3]="http://en.wikipedia.org/wiki/Randomness";
var shuffle = function(array){
var shuffledPages = [];
while(array.length){
shuffledPages.push(array.splice(Math.floor(array.length*Math.random()),1));
}
return shuffledPages;
}
var time = 3300;
var currentIndex = 0;
function pageChange() {
if(currentIndex == 0){
pages = shuffle(pages);
console.log(pages);
currentIndex = pages.length;
}
currentIndex--;
document.getElementById("frame").src=pages[currentIndex];
console.log(currentIndex);
setTimeout(function() { pageChange(); }, time);
};
pageChange();
A variable which can be set to determine if the rotator is running, and setting that to true or false:
var isRunning = true;
....
<button onclick="isRunning = false">stop</button>
<button onclick="isRunning = true">start</button>
And check that inside your method:
function pageChange() {
if(isRunning){
...
}
setTimeout(function() { pageChange(); }, time);
};
Live example: http://jsfiddle.net/xaa1qccm/1/
You may add a start/stop variable so as to check the status :
[...]
var time = 3300;
var currentIndex = 0;
var stop = 0;
function pageChange() {
if(currentIndex == 0){
pages = shuffle(pages);
console.log(pages);
currentIndex = pages.length;
}
if (stop == 0)
{
currentIndex--;
document.getElementById("frame").src=pages[currentIndex];
console.log(currentIndex);
setTimeout(function() { pageChange(); }, time);
}
};
function startStop()
{
if (stop == 0){
stop = 1;
}
else{
stop = 0;
pageChange();
}
}
[...]
And then you call startStop() on the click event of the button you want
Edit : Here is a jsfiddle

javascript autoreload in infinite loop with time left till next reload

i need a JavaScript, that relaods a page every 30 seconds, and will show how much time there is until next reload at the ID time-to-update, Example:
<p>Refreshing in <span id="time-to-update" class="light-blue"></span> seconds.</p>
i also need it to repeat itself infinitely.
thank you for reading, i hope it helps not me but everyone else, and a real big thank you if you could make this script.
(function() {
var el = document.getElementById('time-to-update');
var count = 30;
setInterval(function() {
count -= 1;
el.innerHTML = count;
if (count == 0) {
location.reload();
}
}, 1000);
})();
A variation that uses setTimeout rather than setInterval, and uses the more cross-browser secure document.location.reload(true);.
var timer = 30;
var el = document.getElementById('time-to-update');
(function loop(el) {
if (timer > 0) {
el.innerHTML = timer;
timer -= 1;
setTimeout(function () { loop(el); }, 1000);
} else {
document.location.reload(true);
}
}(el));
http://jsfiddle.net/zGGEH/1/
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds; // Output initial value
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();

Categories

Resources