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);
Related
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.
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)
var i = 3400;
function progress() {
i = 34000;
window.setInterval(function () {
i = i - 100;
document.getElementById("progress").firstChild.data = i;
}, 100);
}
This code is getting faster and faster. The function progress is called every 3 seconds, but I can't change the it's called because it's event based. After around 10 calls i is getting negative!
Umm....
Do not use setInterval
You probably want to use setTimeout
Since progress is called every 3 seconds, you need to avoid that it creates new intervals repeatedly. Using clearTimeout resets the timer anytime you call progress. However, without knowing what exactly you want to achive it's difficult to provide an accurate answer.
var timeout;
function counter(count) {
document.getElementById("progress").firstChild.data = count;
if (count >= 0) {
timeout = window.setTimeout(function() {
counter(count-100);
}, 100);
}
}
function progress() {
window.clearTimeout(timeout);
counter(3400);
}
Try this
var i = 3400;
function progress() {
i = i - 100;
document.getElementById("progress").firstChild.data = i;
window.setTimeout('progress();', 100);
}
In this article, the following function is given to perform an operation x times with setInterval()
setIntervalX(function () {
animateColor();
//or something
}, 3000, 4);
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);
}
what does the callback() do here? I'm trying to do a function after the specified number of repetitions is complete. but this
setIntervalX(function () {
animateColor();
}, 3000, 4, function(){
completeFunction();
});
does not work. Perhaps that syntax is very wrong. I was under the impression that using jquery, you could string together functions like that..
Much grateful for any insight. Thanks!
I think you misunderstood the description slightly. The setIntervalX performs an interaction x times while you want to have a callback function AFTER the iteration.
function setIntervalX(interationFunction, delay, repetitions, callbackFunction) {
var x = 0;
var intervalID = window.setInterval(function () {
iterationFunction();
if (++x === repetitions) {
callbackFunction();
window.clearInterval(intervalID);
}
}, delay);
}
setIntervalX(
function() {
// this executed every time the interval triggers
},
1000, // amount of milliseconds to delay before interval triggers
5, // amount of repetitions before interval is stopped and callback is executed
function() {
// this will be executed after the interval triggered 5 times
// so after round about 5 seconds after setIntervalX was started
}
);
function setIntervalX(func, delay, times, callback) {
if (times > 0) {
setTimeout(function() {
func.apply(arguments.callee);
setIntervalX(func, delay, --times, callback);
}, delay);
} else {
callback.apply(this);
}
}
setIntervalX(function() {
document.write('ping!<br />');
}, 1000, 5, function() {
document.write('Finished!<br />');
});
I personally prefer the setTimeout method... but that is just me. give this a shot and see if it works. demo
Ahh it appears I have misread you're entire post... so Tobias is correct in his reasoning for your question. mine is an example of what you want.
Wow, much simpler with Frame.js:
for(var i=0; i<4; i++){
Frame(3000, animateColor);
}
Frame(completeFunction);
Frame.start();
Both functions would need to call a callback which is passed to them as the first argument:
function animateColor(callback){
// do stuff
callback(); // to advance to the next interval
}
function completeFunction(callback){
// do stuff
callback(); // to advance to conclude the series of Frames
}
callback in the original function is ran on every interval up to X times. Try this modification to allow for a complete callback:
setIntervalX(function () {
animateColor();
//or something
}, 3000, 4, function(){
alert("all done!");
});
function setIntervalX(callback, delay, repetitions, complete) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
complete();
}
}, delay);
}
I'm wondering if there's a way to make setInterval clear itself.
Something like this:
setInterval(function () {
alert(1);
clearInterval(this);
}, 2000);
I want it to keep checking thing if it's finished it will stop.
Try this way:
var myInterval = setInterval(function () {
alert(1);
clearInterval(myInterval);
}, 2000);
Alternative way is using setTimeout() if you know it is just one time call.
(function() {
var runs = 3;
var i = setInterval(function() {
console.log("Number " + runs);
--runs;
if (runs == 0) {
clearInterval(i);
}
}, 1000);
}());
jsfiddle