Issue On Setting Time Out/ Delay on For Loop - javascript

Can you please let me know how I can set timeout / Delay on following code:
$(function() {
var alpha = Array("a","b","c","d","e","f","g","h","i","j","k","l","m","z");
for ( var i = 0; i < alpha.length; i++ ) {
$("#box").html(alpha[i].toUpperCase());
}
});
Demo is Running here
Thanks

Here's a way to do it:
$.each(alpha, function (_, letter) {
$("#box").delay(500).queue(function (next) {
$(this).html(letter.toUpperCase());
next();
});
});
Demo: http://jsfiddle.net/chq22av6/1/

You could call window.setTimeout recursively or use window.setInterval.
These both accept a callback method that will be called based on a timer (number of milliseconds).
Here is an example:
window.setTimeout(function() {
// ... do your work ...
}, 1000 );
You can find more information on MDN.

Here is a working code for you, just use setTimeout.
$(function() {
var alapha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
$.each(alapha, function (index, letter) {
setTimeout(function(){ $("#box").html(letter.toUpperCase())}, index * 100);
});
});
You can change from 100 to another value.. Here is the DEMO..

You'd probably be best served by
window.setInterval(func, delay[, param1, param2, ...])
Calls a function [...] repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.
$(function () {
// pre-process the letter case transform
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
// cache your jQuery object so we're not recreating it 26 times
var $box = $("#box");
// index
var i = 0;
// start an interval and store the id
var intervalID = setInterval(function () {
// set element text
$box.text(alpha[i++]);
// stop the interval after we've processed 26 letters
i > 25 && clearInterval(intervalID);
}, 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box"></div>
See also: clearInterval(intervalID)

Related

How to autorefresh my Ajax inside of a condition [duplicate]

Using setTimeout() it is possible to launch a function at a specified time:
setTimeout(function, 60000);
But what if I would like to launch the function multiple times? Every time a time interval passes, I would like to execute the function (every 60 seconds, let's say).
If you don't care if the code within the timer may take longer than your interval, use setInterval():
setInterval(function, delay)
That fires the function passed in as first parameter over and over.
A better approach is, to use setTimeout along with a self-executing anonymous function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
that guarantees, that the next call is not made before your code was executed. I used arguments.callee in this example as function reference. It's a better way to give the function a name and call that within setTimeout because arguments.callee is deprecated in ecmascript 5.
use the
setInterval(function, 60000);
EDIT : (In case if you want to stop the clock after it is started)
Script section
<script>
var int=self.setInterval(function, 60000);
</script>
and HTML Code
<!-- Stop Button -->
Stop
A better use of jAndy's answer to implement a polling function that polls every interval seconds, and ends after timeout seconds.
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000;
(function p() {
fn();
if (((new Date).getTime() - startTime ) <= timeout) {
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
UPDATE
As per the comment, updating it for the ability of the passed function to stop the polling:
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000,
canPoll = true;
(function p() {
canPoll = ((new Date).getTime() - startTime ) <= timeout;
if (!fn() && canPoll) { // ensures the function exucutes
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
function sendHeartBeat(params) {
...
...
if (receivedData) {
// no need to execute further
return true; // or false, change the IIFE inside condition accordingly.
}
}
In jQuery you can do like this.
function random_no(){
var ran=Math.random();
jQuery('#random_no_container').html(ran);
}
window.setInterval(function(){
/// call your function here
random_no();
}, 6000); // Change Interval here to test. For eg: 5000 for 5 sec
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="random_no_container">
Hello. Here you can see random numbers after every 6 sec
</div>
setInterval(fn,time)
is the method you're after.
You can simply call setTimeout at the end of the function. This will add it again to the event queue. You can use any kind of logic to vary the delay values. For example,
function multiStep() {
// do some work here
blah_blah_whatever();
var newtime = 60000;
if (!requestStop) {
setTimeout(multiStep, newtime);
}
}
Use window.setInterval(func, time).
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function myTimer() {
}
var timer = setInterval(myTimer, 5000);
call this line to stop the loop:
clearInterval(timer);
Call a Javascript function every 2 second continuously for 10 second.
var intervalPromise;
$scope.startTimer = function(fn, delay, timeoutTime) {
intervalPromise = $interval(function() {
fn();
var currentTime = new Date().getTime() - $scope.startTime;
if (currentTime > timeoutTime){
$interval.cancel(intervalPromise);
}
}, delay);
};
$scope.startTimer(hello, 2000, 10000);
hello(){
console.log("hello");
}
function random(number) {
return Math.floor(Math.random() * (number+1));
}
setInterval(() => {
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';//rgb value (0-255,0-255,0-255)
document.body.style.backgroundColor = rndCol;
}, 1000);
<script src="test.js"></script>
it changes background color in every 1 second (written as 1000 in JS)
// example:
// checkEach(1000, () => {
// if(!canIDoWorkNow()) {
// return true // try again after 1 second
// }
//
// doWork()
// })
export function checkEach(milliseconds, fn) {
const timer = setInterval(
() => {
try {
const retry = fn()
if (retry !== true) {
clearInterval(timer)
}
} catch (e) {
clearInterval(timer)
throw e
}
},
milliseconds
)
}
here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
I see that it wasn't mentioned here if you need to pass a parameter to your function on repeat setTimeout(myFunc(myVal), 60000); will cause an error of calling function before the previous call is completed.
Therefore, you can pass the parameter like
setTimeout(function () {
myFunc(myVal);
}, 60000)
For more detailed information you can see the JavaScript garden.
Hope it helps somebody.
I favour calling a function that contains a loop function that calls a setTimeout on itself at regular intervals.
function timer(interval = 1000) {
function loop(count = 1) {
console.log(count);
setTimeout(loop, interval, ++count);
}
loop();
}
timer();
There are 2 ways to call-
setInterval(function (){ functionName();}, 60000);
setInterval(functionName, 60000);
above function will call on every 60 seconds.

Clear all setIntervals

I'm using setIntervals within an each() function like so
$(".elements").each(function() {
setInterval(function() {
}, 1000);
});
Obviously a setIntervals is created for each element.
My question is: How do I clear all the setIntervals when I no longer need them? I have tried storing the setInterval in a variable and call window.clearInterval(int), but that only clears the last setInterval since each variable is overridden.
When you set an interval, you get a pointer to it:
var myInterval = setInterval(function(){}, 4000);
If you want to cancel an interval, you do the following:
clearInterval(myInterval);
So, for what you want to do, you would do the following:
var intervals = [];
$(".elements").each(function() {
var i = setInterval(function() {
}, 1000);
intervals.push(i);
});
Then if you need to cancel them all you can do this:
intervals.forEach(clearInterval);
That should do it for you.
There's no "clear-all-intervals" function.
You'll need to store all of them, and clear all of them:
var ints = [];
$(".elements").each(function() {
ints.push( setInterval(function() {
}, 1000)
);
});
// later
for ( var i = 0; i < ints.length; ++i )
clearInterval( ints[i] );
ints = []; // and forget them
This worked for me:
// clear interval
var id = window.setInterval(function() {}, 0);
while (id--) {
window.clearInterval(id);
var clearAllIntervals = function ( ) {
var intervals = [];
$(".elements").each(function() {
intervals.push( setInterval(function() {
}, 1000) );
});
return function clearAll ( ) {
intervals.forEach( clearInterval );
}
}( );
// When you want to clear them:
clearAllIntervals( );
If you are wanting to be compatible with IE8 or under you should shim .forEach, or replace it with a library equivalent, or a plain loop.
Since each interval is associated with an element, you could store the interval ID in the element:
$(".elements").each(function() {
$(this).data('interval-id', setInterval(function() {
// ...
}, 1000));
});
Then, if you want to clear the intervals,
$(".elements").each(function() {
clearInterval($(this).data('interval-id'));
});
I don't recommend you use this solution, but it really do the trick. The idea it to override setInterval function to collect all links to setInterval:
(function(originalSetInterval){
var intervals = [];
window.setInterval = function(func, timeout) {
var newInterval = originalSetInterval(func, timeout);
intervals.push(newInterval);
return newInterval;
}
window.clearAllIntervals = function() {
intervals.forEach(clearInterval);
}
})(window.setInterval)
To do a better job you would also need to override clearInterval to remove all intervals being clear already:
(function(originalSetInterval, originalClearInterval){
var intervals = [];
window.setInterval = function(func, timeout) {
var newInterval = originalSetInterval(func, timeout);
intervals.push(newInterval);
return newInterval;
}
window.clearInterval = function(interval) {
originalClearInterval(interval);
intervals.splice(intervals.indexOf(interval), 1)
}
window.clearAllIntervals = function() {
intervals.forEach(clearInterval);
}
})(window.setInterval, window.clearInterval)
When you set an interval, you get a pointer to it.
To clear all intervals, you'll need to store all of them:
var arr = [];
arr.push(setInterval(function () {
console.log(1);
}, 1000));
arr.push(setInterval(function () {
console.log(2);
}, 1000));
arr.push(setInterval(function () {
console.log(3);
}, 1000));
Following loop will clear all intervals
// Clear multiple Intervals
arr.map((a) => {
console.log(a)
clearInterval(a);
arr = [];
})
Interestingly, an interval handle ID is an incremental whole number greater than 0. So, all you'd have to do is create a no-function interval, and then for-loop it to clear all intervals from your latest interval handle ID down to 1.
let hInterval1 = window.setInterval(function(){console.log('interval A');},3000);
let hInterval2 = window.setInterval(function(){console.log('interval B');},3000);
for(let i = hInterval2; i > 0; i--) window.clearInterval(i);
If you run that sample, you'll see that we see 2 intervals running in the console emitting "interval A" and "interval B", and then by the time you run the for-loop, it stops both.

Is it unneccesary to break setInterval if element is removed?

I use setInterval as below and until now i have used it exactly same way but if element is removed from Document this interval will continue to work unnecessarily. I haven't seen an example that handle this case yet.
Is it unnecessary to handle this case ? And if i have to handle it so what would be best way break interval ?
var element = $('bla');
setInterval(function () {
element.text(new Date().toString());
}, 1000);
Just a comment:
#hicurin, you might consider using an immediately invoked function expression (IIFE) instead:
(function() {
var element = $('bla');
var interval = setInterval(function () {
element.text(new Date());
// check if element is removed
if(!$('bla').length && interval) {
clearInterval(interval);
}
}, 1000);
}());
Try this:
var element = $('bla');
var int = setInterval(function () {
element.text(new Date().toString());
// check if element is removed
if(!(element.length > 0) || element == undefined){
clearInterval(int);
}
}, 1000);

Increase the value of a number in an element every x milliseconds

So I have this simple HTML:
<span id="badge">0</span>
I want the number 0 to increase by 1 every x milliseconds. How do I do that with Javascript (with or without jQuery)?
Thanks a bunch - I'm new to this :)
You should do this:
<script>
var $badge = $('#badge'); // cache
setInterval(function () {
var value = parseInt($badge.html());
value++;
$badge.html(value);
}, 1000);
</script>
Assuming 1000 milliseconds.
function increment() {
document.getElementById("badge").value = Number(document.getElementById("badge").value) + 1;
setTimeout("increment()",3000);
}
increment()
Every of the answers I see here has the same drawbacks:
performance issue because of selecting the DOM element every ms cycle. Especially when using a heavy library as jQuery.
setInterval() is probably the tool designed for that functionality, but not reliable. It can diverge a lot from the real time, especially when using a small interval. If you want exactly x executions per second, you may google for some timing libraries.
I would code:
var textNode = document.getElementById(badge).firstChild;
var start = Date.now();
window.setInterval(function update() {
textNode.data = Math.round((new Date()-start)/ms);
}, ms);
If you don't want to start at 0, it will be trivial to add an offset (determined before the loop begins), eg.
var start = Date.now() - (textNode.data * ms || 0); // NaN catching, implicit number cast
Something like this?
var millisecs = 10;
setInterval(function() {
var $badge = $('#badge');
$badge.text(parseInt($badge.text())++);
}, millisecs);
http://jsfiddle.net/iambriansreed/MPP8n/3/
Check this http://www.w3schools.com/js/js_timing.asp
A little more about timers:
// setting a variable for your timer will allow you the ability to "turn it on and off"
var tmrChangeI;
// setTimeout is a function to initiate a function once after given amount of milisecs
// whereas setInterval will continue a function until cancled every so many milisecs
// the following wil "turn on" your timer
tmrChangeI = setInterval(function() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
}, 500); // 500 will = every half of a second
// to "turn off" timer
clearInterval(tmrChangeI);
// or set a bool to test and use timeout to repeat till bool is false
var tmrBool = true;
// establish function to execute
function tmrFunc() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
if (tmrBool) tmrChangeI = setTimeout(function() { tmrFunc(); }, 500); // 500 will = every half of a second
};
// execute function, begin timer
tmrChangeI = setTimeout(function() { tmrFunc(); }, 500);
// clear via bool allowing one more execution
tmrBool = false;
// clear by force possibly stoping next execution,
// tho in this manner it may be too late if timer is very short
// and maybe overriden by bool still being true, this is not safest
// but is example of how to use setTimeout
clearTimeout(tmrChangeI);
You can use setInterval.
var $badge = $('#badge');
setInterval(function () {
$badge.html(parseInt($badge.html()) + 1);
}, 1);​//Specify the milliseconds here, right it will update the value every 1 millisecond
Working demo - http://jsfiddle.net/8FMZh/
You could create a Jquery plugin, so you can reuse whenever you need.
$.fn.increment= function(options) {
var $this = $(this);
var coef = options.coef;
var speed = options.speed;
var value = 0;
setInterval(function(){
value = value + coef ;
$this.html(value);
}, speed);
};
And in your main javascript file :
$("#badge").increment({coef: 1, speed:1000});
working demo : http://jsfiddle.net/8FMZh/102/

Queueing setTimeout in javascript

I need to flash an element off and on. This works but I don't really like the code. Is there a nice way of doing this?
setTimeout(function(){
toggle();
setTimeout(function(){
toggle();
setTimeout(function(){
toggle();
setTimeout(function(){
toggle();
}, 100);
}, 100);
}, 100);
}, 100);
I'm using jQuery too if that helps.
function toggle_multiple(n)
{
var toggled = 0;
function toggle_one_time()
{
toggle();
toggled += 1;
if (toggled <= n)
setTimeout(toggle_one_time, 100);
}
toggle_one_time();
}
And just call toggle_multiple(4).
A recursive approach:
function multiTimeoutCall (callback, delay, times) {
if (times > 0){
setTimeout(function () {
callback();
multiTimeoutCall (callback, delay, times - 1);
}, delay);
}
}
Usage:
multiTimeoutCall (toggle, 100, 4);
Edit: Yet another approach, without filling the call stack:
function multiTimeoutCall (callback, delay, times) {
setTimeout(function action() { // a named function expression
callback();
if (--times > 0) {
setTimeout (action, delay); // start a new timer
}
}, delay);
}
I could used arguments.callee instead of a named function expression, but seems that it will be deprecated some day in ECMAScript 5...
Why not use setInterval?
var toggler = function() {
if (++self.counter >= self.BLINK_AMOUNT * 2) {
self.counter = 0;
window.clearInterval(self.timer);
return;
}
toggle();
};
toggler.BLINK_AMOUNT = 1;
toggler.counter = 0;
toggler.timer = window.setInterval(toggler, 100);
I can't remember whether or not IE properly implements the self variable in a timer callback - if it doesn't, use a uniquely named global variable instead.
I would use a blinking effect. For jquery there's pulsate, hope that works for you.
Here's yet another version for simplicity:
for (var i= 0; i<4; i++)
setTimeout(toggle, (i+1)*100);
For larger numbers an interval may be more appropriate, but if it's just four toggles multiple timeouts are fine.
Generalizing 'unknown's' idea of using setInterval,
function schedule(fn, max, delay)
{
var counter = 0;
var interval = setInterval(
function()
{
if(counter++ === max)
clearInterval(interval);
fn();
}
, delay);
}
Usage:
schedule(toggle, 4, 100);
If its just flashing that is required, why not use the jQuery animate ? I use the following to direct user attention to messages. But you can do this for any element -
$("#message_box").fadeOut(450).fadeIn(350);
If you want it multiple times, do this -
$("#message_box").fadeOut(450).fadeIn(350).fadeOut(450).fadeIn(350);
You can do like this:
function toggleMany(cnt) {
toggle();
if (--cnt >= 0) window.setTimeout('toggleMany('+cnt+')', 100);
}
toggleMany(4);

Categories