JavaScript SetInterval() Queue - javascript

Is it possible to call a function with SetInterval() on specific time but execute the function only once.
function get_feed(social) {
$.ajax({})
}
setInterval(function(){
get_feed('facebook');
},5000);
setInterval(function(){
get_feed('twitter');
},10000);
I am expecting result to be called only once on the specify time:
on 5000ms: get_feed('facebook');
on 10000ms: get_feed('twitter');
but currently its calling two functions on 10000ms;

If I'm reading you right, you want to get feeds every five seconds and alternate between facebook and twitter. If so, use a single function:
var feed = "facebook";
setInterval(function() {
get_feed(feed);
feed = feed === "facebook" ? "twitter" : "facebook";
}, 5000);
currently its calling two functions on 10000ms;
That's because your original code schedules get_feed('facebook') to run every 5000ms, and get_feed('twitter') every 10000ms. So after 5000ms, it does the facebook one, then after anothr 5000ms (10000ms in total), it does both of them, then 5000ms later facebook again, then 5000ms (20000ms in total), both of them...

Use setTimeout
function get_feed(social) {
$.ajax({})
}
setTimeout(function(){
get_feed('facebook');
},5000);
setTimeout(function(){
get_feed('twitter');
},10000);

Try
function get_feed(social) {
$.ajax({})
}
var a = setInterval(function(){
get_feed('facebook');
},5000);
var b = setInterval(function(){
get_feed('twitter');
},10000);
Example:
var p = document.getElementById("text");
var a = setInterval(function(){
p.innerText = "facebook";
}, 5000);
var a = setInterval(function(){
p.innerText = "twitter";
}, 10000);
<p id="text"></p>

Related

How to make clearTimeout() happen within setTimeout()?

I have a setTimeout function already running to make a watch work, but I want to clearTimeout on this already running function when I clock on a button, but only after a few seconds. So ideally, I want a clearTimeout() inside another setTimeout() function, but I can't seem to get it working.
I have this code at the moment:
alarm.click(function() {
water.animate(anim);
setTimeout(function () { clearTimeout(time); }, 3000);
});
var time = setTimeout(function(){ startTime() },1000);
But it does it clears it straight away rather than after 3 seconds. What can I do to make it clear after 3 seconds?
edited my code, still not working :(.
You can try:
var time = setTimeout(function(){startTime(time)},1000);
And in startTime you clear time
function startTime(time) {
cleartTimeout(time);
...
}
You are calling it straight away, but you need a callback.
setTimeout(function () { clearTimeout(time); }, 3000);
function startTime() {
document.getElementById('out').innerHTML += 'starttime<br>';
}
function set() {
document.getElementById('out').innerHTML += 'set<br>';
setTimeout(function () {
document.getElementById('out').innerHTML += 'clear3000<br>';
clearTimeout(time);
}, 3000);
}
var time = setTimeout(function () {
document.getElementById('out').innerHTML += 'clear1000<br>';
startTime();
}, 1000);
set();
<div id="out"></div>

Stop JavaScript after execution

How do I stop JavaScript after execution?
I create one javascript for post in chat one text if other people say a keyword.
But the script send the message and not stop.
Now the code:
setInterval(function() {
jQuery('#frame_chatbox')
.replaceWith('<iframe id="framejqs" src="/chatbox" scrolling="yes" width="100%" height="100%" frameborder="0"></iframe>');
jQuery('#framejqs').contents()
.find('#chatbox_footer #chatbox_messenger_form #submit_button')
.click(function() {
if(jQuery('#framejqs').contents()
.find('#chatbox_footer #chatbox_messenger_form input[name="message"]')
.val().indexOf('HERE THE KEYWORD') != -1) {
$.post('/chatbox/chatbox_actions.forum?archives',
{mode:"send", sent:"HERE THE MENS"});
return false;
}
});
});
http://pastebin.com/5KF9R5Rv
It sends the message repeatedly because the sending function is wrapped in an interval firing once per millisecond (the second argument is missing):
setInterval(function () {
// ...
}, time_between_sends);
The time_between_sends defines how much time passes by between different calls of the function you passed into setInterval as first argument.
For example:
setInterval(function () {
console.log(new Date()); // logs the date once per second (1000ms === 1s)
}, 1000);
More generally, I'd consider using an event listener instead of an interval though.
You can simply use clearInterval
var interval = setInterval(function() {
//your code
if(condition to stop interval)
{
clearInterval(interval);//clearing interval when you want
}
});
Here is Live Demo
Update
If you want to stop it after you got response from post method you can do something like following:
DEMO
Code:
var myVar = setInterval(function(){
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
$.post('/echo/html/','',function(){
myStopFunction()//calling method to stop setInterval
});
}, 1000);
function myStopFunction() {
alert("stoping");
clearInterval(myVar);
}

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}

Destroy previous setInterval

I want a function to set an Ajax and a reload timer. The code below doesn't destroy the previous function call timer, so each time I invoke it I get another timer. How can I destroy the previous timer?
function initNowPlayingMeta(station) {
$('#cancion').children().remove();
$('#cancion').load('sonando.php?emisora=' + station);
var prevNowPlaying = setInterval(function () {
$('#cancion').load('sonando.php?emisora=' + station);
}, 5000);
}
You need to store your timer reference somewhere outside of local scope (this essentially means declaring it with var outside of the function). Then, clear it with clearInterval:
var prevNowPlaying = null;
function initNowPlayingMeta(station) {
if(prevNowPlaying) {
clearInterval(prevNowPlaying);
}
$('#cancion').children().remove();
$('#cancion').load('sonando.php?emisora=' + station);
prevNowPlaying = setInterval(function () {
$('#cancion').load('sonando.php?emisora=' + station);
}, 5000);
}
clearInterval
clearInterval(prevNowPlaying);
you will also want to make the prevNowPlaying from previous calls in scope whereever you try to cancel
You need to explicitly clear the timer.
var prevNowPlaying;
function initNowPlayingMeta(station) {
$('#cancion').children().remove();
$('#cancion').load('sonando.php?emisora=' + station);
if (prevNowPlaying === undefined) clearInterval(prevNowPlaying);
prevNowPlaying = setInterval(function () {
$('#cancion').load('sonando.php?emisora=' + station);
}, 5000);
}
For people who only needs to destroy or stop a previous setInterval, not exactly what the question ask (jquery, song, etc)
const previousSetIntervalInstance = setInterval(myTimer, 1000);
//every 1 second update the time
function myTimer() {
  const date = new Date();
  document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function myStopFunction() {
  clearInterval(previousSetIntervalInstance);
}
<h3>setInterval() and clearInterval() demo</h3>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop the time</button>
Initial source: https://www.w3schools.com/jsref/met_win_clearinterval.asp
When you click on stop the time is not updated anymore
Basically, you need to store the setInterval output as global variable and pass it to clearInterval

Resetting a setTimeout

I have the following:
window.setTimeout(function() {
window.location.href = 'file.php';
}, 115000);
How can I, via a .click function, reset the counter midway through the countdown?
You can store a reference to that timeout, and then call clearTimeout on that reference.
// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);
// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);
// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);
clearTimeout() and feed the reference of the setTimeout, which will be a number. Then re-invoke it:
var initial;
function invocation() {
alert('invoked')
initial = window.setTimeout(
function() {
document.body.style.backgroundColor = 'black'
}, 5000);
}
invocation();
document.body.onclick = function() {
alert('stopped')
clearTimeout( initial )
// re-invoke invocation()
}
In this example, if you don't click on the body element in 5 seconds the background color will be black.
Reference:
https://developer.mozilla.org/en/DOM/window.clearTimeout
https://developer.mozilla.org/En/Window.setTimeout
Note: setTimeout and clearTimeout are not ECMAScript native methods, but Javascript methods of the global window namespace.
You will have to remember the timeout "Timer", cancel it, then restart it:
g_timer = null;
$(document).ready(function() {
startTimer();
});
function startTimer() {
g_timer = window.setTimeout(function() {
window.location.href = 'file.php';
}, 115000);
}
function onClick() {
clearTimeout(g_timer);
startTimer();
}
var myTimer = setTimeout(..., 115000);
something.click(function () {
clearTimeout(myTimer);
myTimer = setTimeout(..., 115000);
});
Something along those lines!
For NodeJS it's super simple:
const timeout = setTimeout(...);
timeout.refresh();
From the docs:
timeout.refresh()
Sets the timer's start time to the current time, and reschedules the timer to call its callback at the previously specified duration adjusted to the current time. This is useful for refreshing a timer without allocating a new JavaScript object.
But it won't work in JavaScript because in browser setTimeout() returns a number, not an object.
This timer will fire a "Hello" alertbox after 30 seconds. However, everytime you click the reset timer button it clears the timerHandle then re-sets it again. Once it's fired, the game ends.
<script type="text/javascript">
var timerHandle = setTimeout("alert('Hello')",3000);
function resetTimer() {
window.clearTimeout(timerHandle);
timerHandle = setTimeout("alert('Hello')",3000);
}
</script>
<body>
<button onclick="resetTimer()">Reset Timer</button>
</body>
var redirectionDelay;
function startRedirectionDelay(){
redirectionDelay = setTimeout(redirect, 115000);
}
function resetRedirectionDelay(){
clearTimeout(redirectionDelay);
}
function redirect(){
location.href = 'file.php';
}
// in your click >> fire those
resetRedirectionDelay();
startRedirectionDelay();
here is an elaborated example for what's really going on http://jsfiddle.net/ppjrnd2L/
i know this is an old thread but i came up with this today
var timer = []; //creates a empty array called timer to store timer instances
var afterTimer = function(timerName, interval, callback){
window.clearTimeout(timer[timerName]); //clear the named timer if exists
timer[timerName] = window.setTimeout(function(){ //creates a new named timer
callback(); //executes your callback code after timer finished
},interval); //sets the timer timer
}
and you invoke using
afterTimer('<timername>string', <interval in milliseconds>int, function(){
your code here
});
$(function() {
(function(){
var pthis = this;
this.mseg = 115000;
this.href = 'file.php'
this.setTimer = function() {
return (window.setTimeout( function() {window.location.href = this.href;}, this.mseg));
};
this.timer = pthis.setTimer();
this.clear = function(ref) { clearTimeout(ref.timer); ref.setTimer(); };
$(window.document).click( function(){pthis.clear.apply(pthis, [pthis])} );
})();
});
To reset the timer, you would need to set and clear out the timer variable
$time_out_handle = 0;
window.clearTimeout($time_out_handle);
$time_out_handle = window.setTimeout( function(){---}, 60000 );

Categories

Resources