function setNormal() {
console.log(1)
}
function setAlert() {
console.log(2)
}
function alertFunction() {
alertVar = setInterval(alertFunc, 600);
}
function alertFunc() {
setAlert()
setTimeout(setNormal, 300)
}
alertFunction()
});
how do I make the function alertFunction() run only when (for example) var loop = 1 and then stop when var loop = 0?
(this is my first post to stackoverflow so sorry if I did this wrong)
use setTimeout with a condition.
var x = 1;
setTimeout(function foo(){
// this is a named function expression, foo name only exists inside itself
if(x!==0){
// do some code
console.log("Hello");
setTimeout(foo,1000);
}
},1000);
setTimeout(function(){
// change x after 3 seconds
x = 0;
},3000);
You can also use clear interval to do the same thing
var x = 1;
var interval = setInterval(function (){
if(x!==0){
// do some code
console.log("Hello");
}else{
clearInterval(interval)
}
},1000);
setTimeout(function(){
// change x after 3 seconds
x = 0;
},3000);
Use Like It:-
var alertVar;
function alertFunction() {
alertVar = setInterval(alertFunc, 600);
}
function myStopFunction() {
clearInterval(alertVar);
}
if(lool=1){
alertFunction();
}
if(lool=0){
myStopFunction();
}
Related
I am learning setInterval in JavaScript for the first time, and am trying to show a value after 5 seconds. My code is given below:
<button onclick="myTest()">Try it</button>
<script>
function myTest() {
const ret = myFunction();
alert(ret);
}
function myFunction() {
let i = 0;
const interval = setInterval(function(){
i += 1;
if (i === 5) {
clearInterval(interval);
return i;
}
}, 1000);
}
</script>
I want 5 to be alerted, instead I am getting undefined. Does anyone know why this is happening? Thanks in advance!
You can't return anything from the anonymous function within the setInterval call. You need to write to the console from within that function. Try this:
function myTest() {
// this function is now redundant - you could call myFunction() directly
myFunction();
}
function myFunction() {
let i = 0;
const interval = setInterval(function() {
i += 1;
if (i === 5) {
clearInterval(interval);
console.log(i); // this will appear after 5 seconds...
}
}, 1000);
}
myTest();
return i;
i will be returned to Window (I guess), not to myFunction.
myFunction return undefined by default as you did not write a return .
function myTest() {
myFunction(function(val){
alert(val);
});
}
function myFunction(callback) {
let i = 0;
const interval = setInterval(function(){
i += 1;
if (i === 5) {
clearInterval(interval);
if(callback){
callback(i);
}
}
}, 1000);
}
you can get your value in a callback function .
The alert(ret) will occur before 5 seconds are over and thus my function will return undefined. Try this way.
<button onclick="myTest()">Try it</button>
<script>
function myTest() {
myFunction();
}
function myFunction() {
var i = 0;
var interval = setInterval(function(){
i++;
if (i === 5) {
alert(i);
clearInterval(interval);
}
}, 1000);
}
</script>
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()
})()
I don't even know how to get started with this: I need a for loop that executes a function (say a simple console.log()) with a timed delay between each execution. I've been trying to do it with setTimeout() and it never works. If I call the function that has the loop from setTimeout, it won't work. Ideally I'd want my for loop to print something x times, with a couple of seconds delay between each printing. Any ideas how that might work? I've tried something like this:
function printStuff(){
for(var i=0;i<5;i++){
console.log(i);
}
};
setTimeout(printStuff(),1000);
For me you should execute setInterval and inside this you should increase counter. When counter reach the limit you simply clear interval.
var counter = 0;
var limit = 10;
var myVar = setInterval(function(){
if (counter > limit)
{
clearInterval(myVar);
}
counter++;
console.log("test");
}, 1000);
init();
function init() {
setTimeout(init, 2*1000); // wait 2 sec then call init again
console.log(Date());
}
Or use setInterval:
// Call init after 2 sec and repeat calling it every 2. sec
setInterval(init, 2*1000);
function init() {
console.log(Date());
}
You could use the async module.
var count = 0;
async.whilst(
function () { return count < 5; },
function (callback) {
count++;
console.log(count);
setTimeout(callback, 1000);
},
function (err) {
// 5 seconds have passed
}
);
This way the count will be printed every second
var i = 0;
function timeout(){
setTimeout(log, 1000);
}
function log(){
console.log(i++);
timeout();
}
log();
http://jsfiddle.net/sq4v0kbf/
Use setInterval() instead of setTimeout(). Parameters are just the same:
setInterval(function () {
// your utility code goes here
}, 2000);
Here is one more way to do it. Use a wrapper function.
var time = 2000;
for (var i = 0; i < 10; i++) {
(function (i) {
setTimeout(function () {
console.log(i);
}, time);
})(i);
time+=2000;
}
You can create a sort of delayed loop function with the number of iterations/times you want to run. Something like this:
var delayedLoop = function (n, milliseconds) {
var iteration = function (n) {
if (n > 0) {
n--;
console.log(n);
setTimeout(function () {
iteration(n)
}, milliseconds);
}
};
iteration(n);
}
delayedLoop(4, 1000);
You could even expand the idea and even passing a function to be executed each time.
See demo.
Here's what I think is simpler (and doesn't have the fallbacks of) than a setInterval
var limit = 10,
counter = 0,
delay = 1000;
function doIt() {
document.body.innerHTML += 'Hit counter: ' + (counter++) + '<br />';
if (counter < limit) {
setTimeout(doIt, delay);
}
}
doIt();
And you can generalize it
function runTimedLoop(delay, howMany, callback) {
var index = 0;
function iteration() {
callback(index++);
if (index < howMany) {
setTimeout(iteration, delay);
}
}
iteration();
}
runTimedLoop(1000, 10, function(index) {
document.body.innerHTML += 'Hit counter: ' + (index++) + '<br />';
});
I want to make this counter starts working within 5 seconds of being on the page, but I can not link the setTimeout with setInterval , you would know how could I?
Try to wrap your interval with the setTimeout function:
// interval variable
var cycle = 10;
// variable for the interval since we are invoking it within a function, the callMeEverySecond function can't reach it
var t;
var callMeEverySecond = function() {
cycle--;
// Logs the Date to the console
console.log(new Date());
if(cycle === 0) {
console.log("stop this");
clearInterval(t);
// do something further.
}
}
// Start the timeout after 5 seconds
setTimeout(function() {
// call the function 'callMeEverySecond' each second
t = setInterval(callMeEverySecond, 1000);
}, 5000);
http://devdocs.io/dom/window.settimeout
And a small tutorial: http://javascript.info/tutorial/settimeout-setinterval
Is this ok
var tiempoInicial = 10;
function tiempo() {
document.getElementById('contador').innerHTML='Puedes continuar en ' + tiempoInicial + ' segundos.';
if(tiempoInicial==0) {
clearInterval(t);
document.getElementById("contador").innerHTML = "<p id=\"forumulario\" onclick=\"goToForm1()\">Continuar</p>";
}
}
function iniciar() {
var t = setInterval(tiempo,1000);
clearTimeout(ini);
}
var ini = setTimeout(iniciar, 5000);
Sorry, I tried out the code above and it didn't work so I changed it a bit.
This is the new code.
var tiempoInicial = 10;
function tiempo() {
document.getElementById('contador').innerHTML='Puedes continuar en ' + tiempoInicial + ' segundos.';
tiempoInicial--;
if(tiempoInicial < -1) {
clearInterval(t);
document.getElementById("contador").innerHTML = "<p id=\"forumulario\" onclick=\'goToForm1()\'>Continuar</p>";
}
}
function iniciar() {
t = setInterval(tiempo,1000);
clearTimeout(ini);
}
var ini = setTimeout(iniciar, 5000);
function runAgain()
{
window.setTimeout(foo, 100);
}
function foo()
{
//Do somthing
runAgain();
}
I can use the above code to run a function infinite number of times with an interval of one second.
What is the standard way of running a function defined number of times. Lets say, I want foo() to be run 5 times with an interval of 1 second.
EDIT It's said that global variables should be avoided in Javascript. Isn't there a better way?
With input from answers, I created a function like this: (Working Example: http://jsbin.com/upasem/edit#javascript,html )
var foo = function() {
console.log(new Date().getTime());
};
var handler = function(count) {
var caller = arguments.callee;
//Infinite
if (count == -1) {
window.setTimeout(function() {
foo();
caller(count);
}, 1000);
}
if (count > 0) {
if (count == 0) return;
foo();
window.setTimeout(function() {
caller(count - 1);
}, 100);
}
if (count == null) {foo(); }
};
handler(-1); //Runs infinite number of times
handler(0); //Does nothing
handler(2); //Runs two times
handler(); //Runs foo() one time
var counter = 1;
function foo()
{
if (counter < 5){
counter++
window.setTimeout(foo, 1000);
}
}
foo()// it will run 5 times;
LIVE DEMO
Version with "static variable":
function foo() {
if (typeof foo.counter == 'undefined') {
foo.counter = 0;
}
alert("Run No. " + (++foo.counter));
if (foo.counter < 5) {
setTimeout(function() {
foo(foo.counter + 1);
}, 400);
}
}
foo();
LIVE DEMO
Version with hidden input
function foo() {
var counter = document.getElementById('counter');
var counterValue = parseInt(counter.value, 10);
alert('Run No. ' + counterValue);
if (counterValue< 5) {
counter.value = counterValue + 1;
window.setTimeout(foo, 400);
}
}
foo();
LIVE DEMO
Version with closure :
var x = function() {
var counter = 1;
(function foo() {
alert('Run No. ' + counter);
if (counter < 5) {
counter++;
setTimeout(foo, 400);
}
})();
};
x();
LIVE DEMO
Assuming you have a function:
var foo = function() {
...
};
or if you prefer:
function foo() {
...
}
you could invoke it 5 times at intervals of 1 second like that:
(function(count) {
if (count < 5) {
// call the function.
foo();
// The currently executing function which is an anonymous function.
var caller = arguments.callee;
window.setTimeout(function() {
// the caller and the count variables are
// captured in a closure as they are defined
// in the outside scope.
caller(count + 1);
}, 1000);
}
})(0);
And here's a live demo.
use a global variable and increment it in the function foo() to count the number of times it has been called.
var counter=0;
function runAgain()
{
window.setTimeout(foo, 1000);
}
function foo()
{
//Do somthing
if((++counter)<5)
runAgain();
}
To avoid polluting the global environment with additional variables, you can wrap it in an anonymous function:
(function() {
var counter = 0;
function foo() {
// do stuff
if ((++counter) < 5) window.setTimeout(foo, 1000);
}
})();
function call (func, arg) {
return {
func,
arg,
times: function (num) {
let counter = 0;
while (counter < num) {
this.func(this.arg);
counter += 1;
}
}
};
}
Then to use it, you can do
call(yourFunction).times(10)
or, if you need to enter an argument:
call(yourFunction, arg).times(10)