How can I stop this process after, say, 5 seconds?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function changeBanner(){
// my change banner code
}
window.onload = function () { setInterval(changeBanner, 100) };
</script>
So currently I am changing the banner every 100 milliseconds. But I'd like it to stop after about 5 seconds.
I thought setTimeout might do the trick;
window.onload = function () { setTimeout(setInterval(changeBanner, 100), 5000) };
But that makes no difference.
I'd like it to stop after about 5 seconds.
store the return value given by setInterval and use it with clearInterval
var timer = setInterval(changeBanner, 100);
setTimeout(function() {
clearInterval(timer)
}, 5000);
There are also several libraries that implement function wrappers to achieve the same. For example, in underscore.js you could use _.before:
var changeBannerLimited = _.before(50, changeBanner);
var timer = setInterval(changeBannerLimited, 100);
Note that contrary to using clearInterval this will continue to call the changeBannerLimited function forever, however after being called 50 times (10 * 5 seconds) it will no longer pass the call on to changeBanner.
On a side note I chose underscore.js because I know it well and because it provides nicely formated annotated source code so you can easily understand what's really going on behind the scenes.
You could store the return value of setInterval to a variable so that you can later cancel it:
function changeBanner(){
// my change banner code
}
window.onload = function () {
var id=setInterval(changeBanner, 100);
window.setTimeout(function() {
window.clearInterval(id);
},5000);
};
Use clearInterval.
window.onload = function () {
var bannerInterval = setInterval(changeBanner, 100);
setTimeout(function() {
clearInterval(bannerInterval);
}, 5000);
};
persist setInterval output in variable to be able to call clearInterval;
window.onload = function () {
var job= setInterval(changeBanner, 100) ;
setTimeout(clearInterval(job), 5000)
};
Related
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");
}
simply I want to stop a function after specific time like 5 seconds from calling it.
I couldn't find a way to do it, can somebody help me
function popUp() {
// Do some Thing
});
popUp();
// how to stop popUp() after calling it after 5 seconds from calling it??
You can use setTimout to run a function after a set amount of time. For example:
setTimeout(hidePopup, 5000);
Will run the below function after 5 seconds (5000 milliseconds):
function hidePopup() {
// Do the opposite
}
Just use return statement:
function popUp() {
// Do some Thing
//Timer simulator
for (i = 0; i < 100; i++) {
if (i == 99) return
}
});
How about you call your function, and then call setTimeout inside your function after 5 seconds to change display to "none", like this:
function popUp() {
// Do some Thing
// SetTimeout to change display to none
setTimeout(function () {
document.getElementById('div-id').style.display = "none";
}, 5000);
});
popUp();
I'm trying to have a div's left property change by its self - one every second when your hovering over so I made this:
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
var timerID = setInterval(alert(left_num1), 1000);
//var timerID = setInterval(slideleft(left_num1), 1000);
},function(){
clearInterval(timerID);
});
//function slideleft(left_num){
//$('.license_video').css('left', left_num + "%");
//}
In theory you would think it repeat till you move your cursor off which clears the interval. When I hover over it does it one time and never repeats (there are no errors). Then when I hover off it gives a error "Uncaught ReferenceError: timerID is not defined"
setInterval isn't working at all. You aren't passing it a function as the first argument.
You are calling alert immediately and trying to use it's return value as the function to repeat.
var timerID = setInterval(function () { alert(left_num1) }, 1000);
So you've got two different problems here:
// (1) timerID needs to be defined in a scope accessible to both hover callbacks
var timerID = null;
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
// (2) Pass a *function* to setInterval
timerID = setInterval(function () {
alert(left_num1)
}, 1000);
}, function(){
clearInterval(timerID);
timerID = null;
});
When you write
setInterval(alert(left_num1), 1000);
// or
setInterval(slideleft(left_num1), 1000);
you are passing the value returned by calling alert() or slideleft() (respectively) to setInterval. You are not passing the function itself.
You are assigning null to be the function to call. Why? Because you called alert and assigned its return value to the setInterval parameter.
Instead, use an anonymous function:
setInterval(function() {doStuff();},1000);
Very easy ;-) ... i love jquery, no matter a version... u need javascript pure is send pm me is can help.
umavez = 0;
setInterval(function() {
if (umavez == 0) {
for (x=0;x<10;x++) {
$('div.test').append('<div>'+x+'</div>');
}
}
umavez = 1;
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="test">Linha:</div>
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.
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.