Loop a function until told to stop - javascript

Looking to run a function in coffeescript every minute until a value inputed by user will stop the loop (restart the loop if function called again).
Looking around I assume this has to do with setTimout and clearTimeout?

You can do it with setTimeout (no need for clearTimeout), by re-scheduling the next call each time (setTimeout schedules a one-off call). Or you can use setInterval (which starts a repeated timer) and clearInterval (which stops it).
Starting a repeated timer at 60-second intervals:
timerHandle = setInterval yourFunctionHere, 60000
Or if you want to define an inline function for it:
timerHandle = setInterval ->
yourCodeHere()
return
, 60000
Cancelling it later:
clearInterval timerHandle

Related

How to not wait for code to be executed before going to the next element in array in for-loop

lets say i have a jquery foreach
$(".myClassName").each(function(){
// do stuff that takes 3 seconds to be executed
doStuff();
})
how can i make it so that it dsnt wait for doStuff() to be finnished before executing that code for the next element.
i bascilly want doStuff() to be executed all at the same time, for each element
I actually found a solution,
if you wrap doStuff() in a setTimeout it will work,
this is because setTimeout dsnt pause the code for x amount, it will delay the code for x amount
:)

Need clarification on setTimeout function output

I have one doubt in java script.I opened https://stackoverflow.com and then open developer window(by press f12 or inspect) and went to console and then execute below code.
setTimeout(function(){console.log('hello..')},5000);
output:
8
hello..
once I click on enter first display 8 after 5 sec it displays hello.. text.
Now my question is what is that number here(8), it is changed for different, different domains.
This is the returned value of setTimeout :
The returned timeoutID is a positive integer value which identifies
the timer created by the call to setTimeout(); this value can be
passed to clearTimeout() to cancel the timeout.
That is the ID of the timeout you've just set and you can use it to cancel it.
For example:
var timeoutId = setTimeout(fn, delay);
clearTimeout(timeoutId);
If the clearTimeout function is called before the delay, the fn function will never be executed.
You can find more details about setTimeout HERE

jQuery setInterval from getScript

I am trying to get a script from one page and get it again after a certain period of time. But, the time varies each time. On the main page I have
function varcontent() {
$.getScript("custom.php");
}
varcontent();
Then on the custom.php I have my script and
setInterval(varcontent, 20000);
at the end. Each time it may not be 20 seconds. It seems to work at first, but then the old ones are fired again too. I don't know how to get it out of this loop and they keep multiplying.
You probably want setTimeout, not setInterval. setInterval will keep invoking the callback (until you cancel it), whereas setTimeout will only invoke the callback once after the specified delay.
So in your custom.php, you should have instead:
setTimeout(varcontent, 20000);

Javascript setTimer

I'm having a hard time understanding the logic behind the setTimer method in javascript.
<html><head>
<script>
function Timer () {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
document.getElementById('show').innerHTML=h+":"+m+":"+s;
t = setTimeout("Timer()", 1000);
}
</script>
</head>
<body onload="Timer()">
<div id="show"></div>
</body></html>
setTimeout is used to delay a function/method execution. Then why it is being used in a real-time clock?
t = setTimeout("Timer()", 1000);
This part is confusing.
The clock is recursively calling itself, after the elapsed period of time.
Making a real-time clock is impossible in JS.
Because of how JS engines work, if you put Timer in a loop, to run for an infinite period of time, you'd never see the time update on the screen (as changes aren't drawn to the window until a function finishes and there's a gap in the program).
Also, inside that infinite-loop, it would be impossible to do anything else with the page (even closing it), because JS can only do one thing at a time, so it can't listen to any of the user's clicking until it's done with this loop.......
So that's what the setTimeout is for.
Timer is the function which acts as the clock.
Inside of the Timer function, at the end when all of the work is done, it's telling setTimeout to wait 1 second (1000ms) and then to call a function called Timer.
Timer just so happens to be the same function. But setTimeout doesn't know that, and doesn't care.
The t in this case is largely useless. setTimeout will return a number -- like taking a number at the doctor's office.
If, before you go through with it, you decide to back out, you can call clearTimeout(t); and it'll skip over that call (in this case, it would stop calling the clock).
There are a few bad-practices in here, that I figure I should mention, so that you can try not to copy them in your own practice.
First:
Pass setTimeout a reference to a function, and not a string...
var runThisFunction = function () { console.log("It's the future!"); },
time_to_wait = 250;
// DON'T DO THIS
setTimeout( "runThisFunction()", 250 );
// DO THIS
setTimeout( runThisFunction, 250 );
The difference is that setTimeout will run that string through eval, which can be a huge security concern depending on what you're trying to do.
The second problem is setting a random global variable, t... ...and hoping to use that as a solution.
First, in a couple of years, JS engines are going to start yelling at people for doing that stuff. Second, it's a huge hole, because any part of any app on that page could then overwrite t, or you could be relying on t somewhere else in your script, but every 1000ms, it gets written over with a new number.
Instead, they probably should have used a Timer.start(); and Timer.stop(); setup.
Your code:
t = setTimeout("Timer()", 1000);
The first thing you should know is that it's considered bad practice to put the first parameter in a string -- it should be the function name, unquoted, and without brackets, like so:
t = setTimeout(Timer, 1000);
That aside, your question about why it's being used to display a clock:
The use of setTimeout() inside the Timer() function to call itself is a common Javascript pattern to get a function to be called repeatedly. setTimeout() itself only triggers the function to be called a single time, after the given period of time has elapsed, so for a repeating event it needs to be re-triggered every time.
Since the setTimeout call is inside the Timer() function, it won't be set until Timer() is called the first time by some other means. This is where the body onload comes in.
As you suspect, setTimeout() isn't an accurate method for guaranteeing that a function will be called after exactly a given amount of time. Javascript is not multi-threaded, so any event handlers that are triggered must wait for any other code that is running at the same time. If something else is running slowly, this may cause your timer not to be triggered at exactly the moment it wants to be.
However, this isn't really a problem for your clock , because the clock is setting itself to the actual system time rather than relying on the setTimeout loop to keep itself in sync; the setTimeout loop is simply being used to make sure the display is updated (approximately) once a second. If it isn't actually quite exactly once a second, it doesn't really matter.
I hope that helps explain things a bit better.
When the Timer() function is called, it schedules itself to be run again one second later. The end result is once every second, Timer() updates the show element with the current time. (I have no idea why it's assigned to t, unless t is used in some other code on the page.)
The line starts The function again after one second.

what's the difference between javascript timeout and timer methods

JS support timeout and timer. Here is their definition:
timeout - repeat execution of a code within specific time and it returns an integer that can be used to cancel pending timeout.
var timeout_id = setTimeout(f,500);
cleartTimeout(timeout_id);
timer - repeat exectuion of code at specific interval.
id = setInterval(F,5000);
clearInterval(id)
I am a little confused, what is their difference?
setTimeout executes the code only once.
setInterval executes the code at every xxx amount of time.
Interval repeats indefinitely (unless you clear it)
Timout repeats once (unless you clear it)
See the difference in this demo: http://jsfiddle.net/maniator/KS2pF/
setInterval will continue to run repeatedly until you stop it, setTimeout will run once.
Start using MDN Docs:
setTimeout
setinterval

Categories

Resources