How to perform an action every couple of seconds? - javascript

Can someone quickly and simply explain to me how to perform an action every couple of seconds using
var timeOut = setTimeout(FunctionName, 5000);
I want to run a function every 5 seconds.

As you asked for a method using setTimeout:
function doStuff() {
console.log("hello!");
setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);
But it would probably be better to use setInterval:
function doStuff() {
console.log("hello!");
}
setInterval(doStuff, 5000);

Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.

Use setInterval:
var timeOut = setInterval(nextNotice, 5000);

var myFunction = function() {
//Do stuff
AnotherFunction();
};
var timeOut = setInterval(myFunction, 2000);

you can do something like:
$(document).ready(function ()
{
setTimeout(nextNotice, 5000);
}
function nextNotice()
{
// do stuff
setTimeout(nextNotice, 5000);
}

In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
<html>
<head>
<script type="text/javascript">
var c = 0;
var t;
var timer_is_on = false;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout(timedCount, 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = true;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

Related

Clear timeout of a functions inside global function

I have set a function that loads on document ready with name myFunction. There are 5 functions inside it with different timeouts. I want to clearTimeout of 3rd and 4th functions on clicking a button inside my html code with id #btn . Here is my code
<doctype! HTML>
<html>
<head>
<title>
My Page
</title>
<script src="jquery-3.2.1.js">
<script src="myScript.js">
<script type="text/javascript">
$(document).ready(myFunction);
</script>
</head>
<body>
<button id="btn">
</body>
</html>
myScript.js is below
function myFunction(){
setTimeout(function function1(){
// do stuffs
}, 5000);
setTimeout(function function2(){
// do stuffs
}, 10000);
setTimeout(function function3(){
// do stuffs
}, 15000);
setTimeout(function function4(){
// do stuffs
}, 20000);
setTimeout(function function5(){
// do stuffs
}, 25000);
}
To clear a timeout, you must assign it to a variable which holds the reference. Here is an example:
var t1,t2,t3,t4,t5;
function myFunction(){
t1 = setTimeout(function function1(){
// do stuffs
}, 5000);
t2 = setTimeout(function function2(){
// do stuffs
}, 10000);
t3 = setTimeout(function function3(){
// do stuffs
}, 15000);
t4 = setTimeout(function function4(){
// do stuffs
}, 20000);
t5 = setTimeout(function function5(){
// do stuffs
}, 25000);
}
function myClearFunction(){
clearTimeout(t3);
clearTimeout(t4);
}
Call myClearFunction() from your button to clear the third and forth timers.
You can use clearTimeout for this. Here's a functional demo:
var timer1 = setTimeout(function() {
console.log('timer1');
}, 5000);
var timer2 = setTimeout(function() {
console.log('timer2');
}, 10000);
var timer3 = setTimeout(function() {
console.log('timer3');
}, 15000);
var timer4 = setTimeout(function() {
console.log('timer4');
}, 20000);
var timer5 = setTimeout(function() {
console.log('timer5');
}, 25000);
document.getElementById('x').addEventListener('click', function() {
clearTimeout(timer3);
clearTimeout(timer4);
});
<button id="x">Stop Timer 3 and 4</button>
SetTimeout returns a value, save that for timer 3 and 4 and then on click button click cancel those. Make sure to check if the values for 3-4 are defined before calling clear on them.
Return Value: A Number, representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer
from https://www.w3schools.com/jsref/met_win_settimeout.asp

Manually set interval time for setInterval

I'm trying to create application where the user can select how often they want the counter to increment by. For example, they type into the input box that they want it to increment by 1 every 5 seconds, and the setInterval will be set to 5 seconds, etc. Here's what I have so far:
<input type="text" id="timer"></input>
<input type="button" onlick="setTime()" value="test" />
<h1>0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>
<script type="text/javascript">
function setTime() {
var output = $('h1');
var isPaused = true;
var count = 0;
timer = document.getElementById("timer").value;
setInterval(function() {
if(!isPaused) {
time++;
output.text(time);
}
}, timer*1000);
}
//with jquery
$('.pause').on('click', function(e) {
e.preventDefault();
isPaused = true;
});
$('.play').on('click', function(e) {
e.preventDefault();
isPaused = false;
});
</script>
Can I get any ideas or help? I appreciate it in advance
Refactoring a little your code, you can do it this way:
Every <input type="text" id="timer"></input>Seconds<br>
<button class="start">Start</button>
<h1>0</h1>
<button class="play">Play</button>
<button class="pause">Pause</button>
And the JS:
var interval = null;
var time = 0;
var output = $('h1');
function setTimer() {
var seconds = +($("#timer").val());//Get the user input (and convert to number)
interval = setInterval(function() {
time++;
output.text( time );
}, seconds*1000);
}
//with jquery
$('.pause').on('click', function(e) {
e.preventDefault();
if(interval){
clearInterval(interval);//Clear the created interval
}
});
$('.play').on('click', function(e) {
e.preventDefault();
setTimer();
});
$('.start').click(function(){
time = 0;
setTimer();
});
See the working example here: https://output.jsbin.com/cukehijuwo/
Each time the user calls setTime, you are creating another interval. These will continue to be created throughout the lifecycle of your application. You should remove timeouts before creating new ones:
var timeoutID = null;
function setTime() {
...
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
...
}, timer * 1000);
}
For reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
Full simple tested program, hope this will help you
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
function display() {
$("h1").html(parseInt($("#inc").val()) + parseInt($("h1").html())) ;
t = setTimeout("display()",parseInt($("#int").val())*1000)
}
function pauseT(){
clearTimeout(t);
}
function continueT(){
t = setTimeout("display()",parseInt($("#int").val())*1000)
}
</script>
Increment Value<input type="text" id="inc"></input>
Interval in Second<input type="text" id="int"></input>
<input type="button" onclick="display()" value="Start" />
<h1>0</h1>
<button onclick="continueT()">Continue</button>
<button onclick="pauseT()">Pause</button>

setInterval & setTimeout?

I want to stop my javascript after x seconds, I saw that the function is setTimeout, I tried to add that to my code but no succes, is this the better way to do this?
Thanks for your help !
<html>
<head>
<script type="text/javascript">
function blink(){
state = document.getElementsByTagName('img')[0].style.visibility;
if(state == 'hidden'){
newState = 'visible';
}else if(state == 'visible'){
newState = 'hidden';
}
document.getElementsByTagName('img')[0].style.visibility = newState;
}
setInterval('blink();', 300);
</script>
</head>
<body>
<img src="http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg" style="visibility:hidden">
</body>
</html>
Initialize your interval in a variable and clear it after X (here 2) seconds:
var interval = setInterval(blink, 300);
setTimeout(function() {
clearInterval(interval);
}, 2000);
use like this:
var myvar;
function myStartFunction()
{
myvar=setInterval(function(){blink()},300);
}
function myStopFunction()
{
clearInterval(myvar);
}

Can I have setInterval and setTimeout at the same time?

According to this thread: how many javascript setTimeout/ setInterval call can be set simultaneously in one page? it is possible to have multiple setIntervals at the sametime.
However, is it possible to have a setInterval and setTimeout at the sametime?
This is not working...
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
init();
});
function init() {
$('#startbutton').on('click', handleClick);
}
</script>
</head>
<body>
<script>
var playBeep = function () {
var snd = new Audio("beep-7.wav");
snd.play();
}
var handleClick = function () {
var interval1 = setInterval(updateDisplay, 1);
makeIntervals([1,2,3], playBeep);
}
var makeIntervals = function(timeList,callback){
intervals = []
for(i in timeList){
intervals.push(setTimeout(callback,timeList[i]))
}
return intervals
}
function updateDisplay() {
var value = parseInt($('#timer').find('.value').text(), 10);
value++;
$('#timer').find('.value').text(value);
}
</script>
<button type="button" id="startbutton">Play Beep</button>
<P>
<div id="timer"><span class="value">0</span> ms</div>
<P>
Of course. However just make sure you don't have too many.

Can a body tag hold multiply onload="setInterval()"?

Can a body tag hold two set intervals? or have 2 functions use the same interval?
ex:
<body onload="setInterval(function1, 500); setInterval(function2, 1000);">
<body onload="setInterval(function1, function2, 500");>
You can create a function that calls setInterval() twice with the different functions and call it on the body.onload().
And i dont think that 2 functions can have the same interval unless you wrap them up in one or call them inline like this:
<body onload="setInterval(function(){ function1(); function2();}, 500);">
Your first example would be fine:
window.onload = function() {
setInterval(function1, 500);
setInterval(function2, 1000);
}
function function1() {
console.log("function1");
}
function function2() {
console.log("function2");
}
See an example of the above code working here.
Simply use jQuery and register an event handler (in a <script type="text/javascript"> block).
In case all you need is the DOM tree being available:
$(document).ready(function() {
setInterval(function1, 500);
setInterval(function2, 1000);
});
otherwise (if you need all images being loaded etc):
$(window).load(function() {
setInterval(function1, 500);
setInterval(function2, 1000);
});
Instantiate as many onloads as you need without the collisions.
<SCRIPT>
// Class Definition
OnLoad = function(taskFunction,miliseconds) {
var context = this;
context.cnt = 0;
context.id = null;
context.doTask=taskFunction;
context.interval = function() {
if(document.readyState == "complete"){
try{ context.stop();} catch(e){ throw new Error("stop error: " + context.id); }
try{ context.doTask();} catch(e){ throw new Error("load error: " + context.id); }
}
};
context.start = function(timing) {
if(context.id && context.id!=null)
context.stop();
context.cnt=0;
context.id=setInterval(context.interval,timing);
};
context.stop = function() {
var _id = context.id;
clearInterval(context.id);
context.id=null;
};
context.start(miliseconds ? miliseconds : 100);
};
// Example Onloads
new OnLoad(function(){
alert("onload 1");
}); // uses default timing of 100 miliseconds
new OnLoad(function(){
alert("onload 2");
},200);
new OnLoad(function(){
alert("onload 3");
},300);
</SCRIPT>
Try This Cod it's Easy.
you can run this here and TEST it.
window.onload = function() {
function foo() {
Load_Note();
}
setInterval(foo, 3600);}
function Load_Note() {console.log("api loded")}

Categories

Resources