Javascript: Call a function after specific time period - javascript

In JavaScript, How can I call a function after a specific time interval?
Here is my function I want to run:
function FetchData() {
}

You can use JavaScript Timing Events to call function after certain interval of time:
This shows the alert box every 3 seconds:
setInterval(function(){alert("Hello")},3000);
You can use two method of time event in javascript.i.e.
setInterval(): executes a function, over and over again, at
specified time intervals
setTimeout() : executes a function, once, after waiting a
specified number of milliseconds

Execute function FetchData() once after 1000 milliseconds:
setTimeout( function() { FetchData(); }, 1000);
Execute function FetchData() repeatedly every 1000 milliseconds:
setInterval( FetchData, 1000);

ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:
setTimeout(function() { FetchData(); }, 1000)
Instead, you can use annonymous arrow function which looks cleaner, and less confusing:
setTimeout(() => {FetchData();}, 1000)

sounds like you're looking for setInterval. It's as easy as this:
function FetchData() {
// do something
}
setInterval(FetchData, 60000);
if you only want to call something once, theres setTimeout.

Timeout:
setTimeout(() => {
console.log('Hello Timeout!')
}, 3000);
Interval:
setInterval(() => {
console.log('Hello Interval!')
}, 2000);

setTimeout(func, 5000);
-- it will call the function named func() after the time specified.
here, 5000 milli seconds , i.e) after 5 seconds

Related

How do i make a javascript fuction repeat every few seconds? [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");
}

How to make setInterval() to wait for an interval (like 10 seconds) before EVERY iteration?

The normal behavior of setInterval(function() {...}, intervalInMilliseconds) in Javascript is such that it is called for the first time after intervalInMilliseconds milliseconds, and after that continues to run again and again without any delay or wait.
I need my code to be executed after every, say, 10 seconds. The following will execute the function for the first time after 10 seconds and then continue to execute it again and again (until clearInterval() is called) without any delay/wait.
setInterval(function() {
//code, e.g. some AJAX request
}, 10000);
I need each iteration to be executed after a 10 seconds delay. How can I do that?
So, as I understand it, you want the "loop" to execute 10 seconds after your code has completed? If so, you could do something like this...
Execute your synchronous long running code
Execute another loop, 10 seconds later (I've used 1 second in the example)
Synchronous example...
var loop = () => {
setTimeout(() => {
doSyncWork()
loop()
}, 1000)
}
loop()
Or asynchronously (e.g. ajax)...
var loop = () => {
setTimeout(() => {
doAsyncWithCallback(loop)
}, 1000)
}
loop()
Or with a Promise...
var loop = () => {
setTimeout(() => {
doAsyncWithPromise().then(loop)
}, 1000)
}
loop()
The normal behavior of setInterval(function() {...},
intervalInMilliseconds) in Javascript is such that it is called for
the first time after intervalInMilliseconds milliseconds, and after
that continues to run again and again without any delay or wait.
thats not true.
mormal behavior of setInterval is to execute callback every n milliseconds.
every callback call will occur after previous callback invocation over n milliseconds.
take a look
let counts = 0;
let interval = setInterval(() => {
console.log(counts % 2 == 0 ? 'tick' : 'tack');
counts++;
if (counts == 5)
clearInterval(interval);
},1000);
I need each iteration to be executed after a 10 seconds delay. How can
I do that?
like this:
setInterval(callback, 10000);
every callback will be called each ten seconds

setTimeout only executes once

Why is the setTimeout only being called once?
repeatSubscriber = function(observer) {
observer.next('first');
(function() {
setTimeout(() => {
observer.next('repeating timed resp');
}, 3000);
}());
};
Prints:
first
repeating timed resp
setTimeout() is only supposed to trigger once - what you need is setInterval().
Because it should:
setTimeout() sets a timer which executes a function or specified piece of code once after the timer expires.
More at MDN
What you are looking for is setInterval()
repeatSubscriber = function(observer) {
observer.next('first');
(function() {
setInterval(() => {
observer.next('repeating timed resp');
}, 3000);
}());
};
Because it worked like this its in the function nature,
If you need repeated call you need setInterval function

javascript wait specific amount of time before executing a function

is there any way to delay a function in javascript I want to do such thing:
function showLabel(){
document.getElementById(id).show();
wait(5000); //wait 5 sec
document.getElementById(id).hide();
}
I want to show a label for 5 sec if this function is called, there may be another way to do so.
Note: I can't use jQuery
Hint: Use setTimeout
window.setTimeout("javascript function", milliseconds);
Read the docs and find out how to do it: https://developer.mozilla.org/en/docs/Web/API/window.setTimeout
If you want something like sleep then:
function sleep(millis, callback) {
setTimeout(function()
{ callback(); }
, milliseconds);
}
I'd prefer:
function doStuff()
{
//do some things
setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}
function continueExecution()
{
//finish doing things after the pause
}
Another way using loop
<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
var startTime = new Date().getTime(); // get the current time
while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>
You may try this:
function showLabel(){
document.getElementById(id).show();
setTimeout(function()
{
document.getElementById(id).hide();
}, 5000);
}
Use setTimeout for one time task, else setInterval for repetitive task.
use setTimeout function in javascript. and clear the time out one the function call over
var timerId = setTimeout(function showLabel(){
document.getElementById(id).show();
document.getElementById(id).hide();
}, 5000);
clearTimeout(timerId);
setTimeout(
function(){ Your_function }, milliseconds
);
This calls the function after the given time is up.

setTimeout functionality is not working

I am trying to use the jQuery setTimeout in order to call a method each x time interval:
$('.text').blur(function () {
doSmth();
});
$('.text').bind("paste", function (e) {
setTimeout(function () {
doSmth();
}, 5);
});
The timeout is not working , please advice !
What do you mean with "it's not working"?Anyway setTimeout() is a Javascript function that triggers only once after the specified interval.
If you wan't to trigger something every five second you should do:
var interval = setInterval(doSmth, 5000);
Where doSmth is a function defined elsewhere and 5000 is the number of millisecond of the interval. If yo want to stop the execution just do:
clearInterval(interval);
First, it isn't a "jQuery setTimeout". setTimeout is part of the native API, not jQuery's API.
Second, I assume you want 5 seconds. Currently you're doing 5 milliseconds.
$('.text').bind("paste", function(e) {
setTimeout(function() {
doSmth();
}, 5000);
});
The duration of 5 in your code is far too short to be perceptible.
I see that the other answers user setInterval, but from what I've read, you should avoid using setInterval, since you can end up with a stack of not-yet-executed function calls etc.
So what you could do instead is something like this:
var myTimeout;
$('.text').bind("paste", function (e) {
function loopFunction () {
doSmth();
myTimeout = setTimeout(loopFunction, 5000);
}
myTimeout = setTimeout(loopFunction, 5000);
});
Now you have a function that calls itself every five seconds.
According to your feedback,here is the solution:
var interval = setInterval(doSmth, 5000);
$('.text').blur(function() {
doSmth();
});
$('.text').bind("paste", function(e) {
setTimeout(function() {
doSmth();
}, 0);
});
Thanks for you amazing support.

Categories

Resources