setInterval for variable to be false - javascript

So I basically got a variable that is set to true, and what I want to achieve is so the variable turns to false after 2 seconds. How can I do this with the use of setInterval ?

Try using setTimeout instead. It will execute the anonymous function once.
var yourVar = true;
setTimeout(function(){ yourVar = false; }, 2000);

If you are trying to trigger some event or call some functions after 2 seconds, then:
setTimeout(function() {
function1();
function2();
}, 2000);
// this will call functions after 2 seconds, when setTimeout will get called
And, if you want to call some functions after some particular event (condition) using setInterval then you have to use clearInterval to break the loop:
var setint = setInterval(function(){
if (check condition here) {
function1();
function2(); // .... so on
clearInterval(setint); // break the setInterval loop
}
}, 100);

Related

How would I make this function repeat? [duplicate]

I want repeat this code every 4 seconds, how i can do it with javascript or jquery easly ? Thanks. :)
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup);
$("#prompt").animate({"top": "+=25px"}, 500).delay(2000).animate({"top": "-=25px"}, 500).delay(500).html("");
}
});
Use setInterval function
setInterval( fn , miliseconds )
From MDC docs:
Summary
Calls a function repeatedly, with a fixed time delay between each call to that function.
Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);
where
intervalID is a unique interval ID you can pass to clearInterval().
func is the function you want to be called repeatedly.
code in the alternate syntax, is a string of code you want to be executed repeatedly. (Using this syntax is not recommended for the same reasons as using eval())
delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.
Example
// alerts "Hey" every second
setInterval(function() { alert("Hey"); }, 1000);
setInterval(function(){
// your code...
}, 4000);
It's not too hard in javascript.
// declare your variable for the setInterval so that you can clear it later
var myInterval;
// set your interval
myInterval = setInterval(whichFunction,4000);
whichFunction{
// function code goes here
}
// this code clears your interval (myInterval)
window.clearInterval(myInterval);
Hope this helps!
Another possibility is to use setTimeout, but place it along with your code in a function that gets called recursively in the callback to the $.get() request.
This will ensure that the requests are a minimum of 4 seconds apart since the next request will not begin until the previous response was received.
// v--------place your code in a function
function get_request() {
$.get("request2.php", function(vystup){
if (vystup !== ""){
$("#prompt").html(vystup)
.animate({"top": "+=25px"}, 500)
.delay(2000)
.animate({"top": "-=25px"}, 500)
.delay(500)
.html("");
}
setTimeout( get_request, 4000 ); // <-- when you ge a response, call it
// again after a 4 second delay
});
}
get_request(); // <-- start it off
const milliseconds = 4000
setInterval(
() => {
// self executing repeated code below
}, milliseconds);
Call a Javascript function every 2 second continuously for 20 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");
}

Javascript - Disable all nested functions for some time after one function function has been executed

After a function has run I want to disable a whole set of functions can be executed again. I thought the most logical way would be to put them all together inside an overarching function (in this case function run) and disable that function for some time.
So for example in the code below, when function exampleOne is executed I want to disable the whole run function for X time before it can run again.
function run(){
function exampleOne(){
// Code
sleep(1000);
}
function exampleTwo(){
// Code
sleep(1000);
}
}
run();
Take a look at underscore.js and especially the throttle or debounce functions.
You can define your functions as variables then you can disable them by assigning an empty or error functions to these variables. Two functions (e.g. enable/disable) can be responsible to disable/enable the whole set of functions. and of course you can use setTimeout to manage the delay.
for example:
var exampleOne, exampleTwo;
function enable(){
exampleOne = function(){
// do something
disable();
setTimeout(function() { enable(); }, 10000);
}
exampleTwo = function(){
// do something
disable();
setTimeout(function() { enable(); }, 10000);
}
}
function disable(){
exampleOne = function(){
Alert("i'm sleep!")
}
exampleTwo = function(){
// do nothing
}
}
enable();

javascript setTimeout function does not work

I am trying to update a variable every one second. For that reason I am using setTimeout. But it does not update the variable. It logs out 0 just once. Here is my code
var yes=0;
setTimeout(function () {
console.log(yes);
yes++;
}, 1000);​
Use setInterval, to finish the repitition you have to clear the interval using clearInterval(yourInterval);
Live Demo
var yes=0;
yourInterval = setInterval(function () {
console.log(yes);
yes++;
}, 1000);​
setTimeout does repeat itself only once, try setInterval so that for every second it increments yes with 1
but remember to clear the interval after sometime else you get on to a never ending loop
using clearInterval()
setTimeOut method is just called once after a specific timeout which in your case is 1000, try to use setInterval method instead
jsBin demo with setTimeout
If you really want to stick to setTimeout (I appreciate that ;) )
than just wrap all into a function and recall it inside it self like:
var yes=0;
(function loop(){
setTimeout(function () {
console.log(yes);
yes++;
loop(); // loop recall
}, 1000);
})();
Otherwise go for setInterval:
var yes=0;
function count(){
console.log(yes);
yes++;
}
setInterval(count, 1000);

jquery delay between javascript functions

I have multiply functions with parameters simplified as:
function f1(p1,p2){
alert('Function one is P1:'+p1+' P2:'+p2);
}
function f2(p1,p2){
alert('Function two is P1:'+p1+' P2:'+p2);
}
I need to fire these is a sequence with a delay between. I have however found that jQuery dislikes running functions with parameters. I have tried the .click function.
$.delay(1000).click(f1('One',false)).delay(1000).click(f2('One',false));
But the delay makes the click functions not work...
I would just use a simple timeout:
f1("one", false);
setTimeout(function() { f2("one", false); }, 1000);
$.delay(1000).click(function(){f1('One',false);}).delay(1000).click(function(){f2('One',false);});
not sure what the click is for though ...
if you want to delay a function call then a much simpler way is to use setTimeout().
eg:
// calling it in a nested setTimeout for sequential delayed execution
setTimeout(function(){
f1('One',false);
setTimeout(function(){
f1('One',false)
},300)
},300)
function fn1()
{
alert(1);
}
function fn2()
{
alert(2);
}
var arr=[fn1,fn2];
var len=arr.length;
var time=1000;
for(var k=0;k<len;k++)
{
(function(k)
{
setTimeout(arr[k],time);
}(k))
time=time*2;
}
It executes after a delay of 1 second!
DEMO

Best way to put delay after calling javascript functions

I'm using jquery to call some javascript functions with a delay between them.
Also I'm using Jquery Wait
When I call below function,all functions are called recpectively,there are no delays between each other.
$(this)
.call(f1)
.wait(5000)
.call(f2)
.wait(5000)
.call(f3);
Here call function calls some function as I did
$.fn.call = function (f) {
if (f)
f();
return this;
};
What am i doing wrong ?
How can i achieve something like this ?
Thank you
If you want to call a function every 5 seconds use
setTimeout(function(){f1},5000);
setTimeout(function(){f2},10000);
setTimeout(function(){f2},15000);
if you want to call each function 5 seconds after the last one terminated use
setTimeout(function(){f1;setTimeout(function(){f2;setTimeout(function(){f3},5000);},5000);},5000);
You don't need wait() from that cookbook; delay() is built-in and appears to have the same functionality. But either function involves adding something to jQuery's internal queue of effects and then removing it after a timeout expires, i.e. it's not a sleep statement, so it's not going to wait around before returning.
If you want to use delay() or wait(), you should make call() enqueue the function with queue(). Just sketching, but something like:
$.fn.call = function(f) {
if (f) {
$(this).queue(function() {
f();
$(this).dequeue();
}
}
return this;
}
Then I'd expect your code to work the way you intend.
Here is a function that calls in sequence an array of function:
$.fn.callFn = function(fns, delay) {
var fn, that = this;
if(fns.length > 0){
fn = fns.shift()
fn && fn();
setTimeout(function(){
that.callFn(fns, delay);
}, delay);
}
return this;
};
And you would call it like that:
$(this).callFn([f1, f2, f3], 2000);
$('#box').slideUp(300).delay(800).fadeIn(400);
/* .delay = wait time = 800 (this means it will wait 800/1000 of a second/ "1000 = 1 second") */

Categories