setTimeout and setInterval not working - javascript

I want to be able to call the function work() every 6 seconds. My jQuery code is
function looper(){
// do something
if (loopcheck) {
setInterval(work,6000);
}
else {
console.log('looper stopped');
}
}
The problem I am running into is that it loops over work twice quickly, and then it will wait for 6 seconds. i tried using setTimeout with similar results.
What could be causing work to be called twice before the delay works?

setInterval should be avoided. If you want work to be repeatedly called every 6 seconds, consider a recursive call to setTimeout instead
function loopWork(){
setTimeout(function () {
work();
loopWork();
}, 6000);
}
Then
function looper(){
// do something
if (loopcheck) {
loopWork()
}
else {
console.log('looper stopped');
}
}
And of course if you ever want to stop this, you'd save the value of the last call to setTimeout, and pass that to clearTimeout
var timeoutId;
timeoutId = setTimeout(function () {
work();
loopWork();
}, 6000);
Then to stop it
clearTimeout(timeoutId);

Use old-style setTimeout()
var i=0;
function work(){
console.log(i++);
}
function runner(){
work();
setTimeout(runner, 6000);
}
runner();

I prefer the following pattern myself I find it easier to follow:
function LoopingFunction() {
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
And if you want to be able to stop it at any point:
var LoopingFunctionKeepGoing = true;
function LoopingFunction() {
if(!LoopingFunctionKeepGoing) return;
// do the work
setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}
Now you can stop it at any time by setting LoopingFunctionKeepGoing to false.

Related

javascript: how can I stop a function after specific time from calling it

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();

Using clearInterval within a function to clear a setInterval on another function

I think im missing something fairly obvious with how the clearInterval method works.
So with the code below. I would expect the first function call to execute testFunction and set the interval to repeat the function. The 2nd call would execute the second function which will remove the interval from the 1st function. As this would execute far before the 5000ms interval the first function would not be executed again. However it does not behave like this.
Could someone please explain what is wrong with my method?
Reason for this is in a program I am writing I am making repeated get requests, every 30 seconds or so , using setTimeout but i would like a method to easily remove this interval at other points in the program
function testFunction() {
$("#test").append("test");
setTimeout(testFunction, 5000);
}
function stopFunction() {
clearTimeout(testFunction);
}
testFunction();
stopFunction();
setTimeout returns an ID so you should
var timeoutID = setTimeout(blah blah);
clearTimeout(timeoutID);
setTimeout returns an object that you need to pass into the clearTimeout method. See this article for an example: http://www.w3schools.com/jsref/met_win_cleartimeout.asp
setTimeout returns an identifier for the timer. Store this in a variable like:
var timeout;
function testFunction(){
...
timeout = setTimeout(testFunction, 5000);
}
function stopFunction(){
clearTimeout(timeout);
}
Here is a simple and I think better implementation for this .
var _timer = null,
_interval = 5000,
inProgress = false,
failures = 0,
MAX_FAILURES = 3;
function _update() {
// do request here, call _onResolve if no errors , and _onReject if errors
}
function _start() {
inProgress = true;
_update();
_timer = setInterval(_update, _interval);
}
function _end() {
inProgress = false;
clearInterval(_timer);
}
function _onReject(err) {
if (failures >= MAX_FAILURES) {
_end();
return false;
}
_end();
failures++;
_start();
}
function _onResolve(response) {
return true;
}

How to create a function setInterval with clearInterval inside it?

I have a app that must send the user to homepage after some events. For this I use this bit of code that works good:
var waitime = 1000;
var handle=setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
But I was trying to create a function to be called instead copy the code every time. So, after some reseach setInterval and how to use clearInterval and clearInterval outside of method containing setInterval I have create this one:
function refreshToHomePage3(handle,waitime){
return setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
}
The problem is when a call the function, like this:
var refreshIntervalId=refreshToHomePage3(refreshIntervalId,waitime);
I have a infinite loop. I already solved the problem using setTimeout instead of setInterval and the function became like this one:
function refreshToHomePage2(waitime){
setTimeout(function () {
$('.wrapper').html(divResposta);
$('body').append(js);
}, waitime);
}
But I was wondering how to solve the problem using setInterval and clearInterval. Any thougths?
setTimeout is prefered here. But you can use setInterval like this..
function refreshToHomePage3(handle,waitime){
handle = setInterval(function () {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
return handle;
}
Actually there is no need to pass a handle variable into the function.
function refreshToHomePage3(waitime){
var handle = setInterval(function () {
alert("called after waitime");
clearInterval(handle);
}, waitime);
return handle;
}
var handle = refreshToHomePage3(5000);
You're clearing the interval after the first time the code runs. So what you're doing is just what setTimeout does. You need setTimeout which runs only once after the waiting for waitTime.
function refreshToHomePage(handle, waitime) {
setTimeout(function() {
$('.wrapper').html(divResp);
$('body').append(js);
clearInterval(handle);
}, waitime);
}
If you want your code to be executed just once after the wait time, setInterval is not the right function for this job, but setTimeout is.
setInterval will execute your code every n seconds until you execute clearInterval. However, setTimeout will execute your code once after n seconds and is therefore the correct approach for your problem.
Don't try to make setInterval something that it isn't :)

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