Stop JavaScript after execution - javascript

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

Related

JavaScript SetInterval() Queue

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>

How can I depend on the interval that I just cleared in jquery?

It's a follow up to this question - https://stackoverflow.com/a/33430608/3766930
Basically I have a text area and when user starts typing in sth, the counter starts going down from 3 to 0. when it reaches 0 it gets disabled.
Now I want to add a feature of starting over - when user clicks the link start over, text area goes enabled again and user has 3 seconds (again) to perform the input.
I modified the jquery script:
$('#textArea').on('input propertychange', display30Seconds);
var interval;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
}
}, 1000);
}
but I see that I cannot call the method display30Seconds(); again. Or rather I can, but the interval is not set again. How can I fix it?
Seems like I'm not entering the code inside
if (!interval)
because the interval is not visible any more after clearing it (?). So I thought about moving the var interval; into the body of the method function display30Seconds() {, but that doesn't bring the expected effect. Is there a way of fixing it?
Here is my updated fiddle: http://jsfiddle.net/jf4ea4nx/3/
Set interval=null after the clearInterval() call.
What seems to confuse you is the semantics of clearInterval(interval). As Patrick Evans points out in his comment, it will not set interval to a value that evaluates to false in a condition.
To make it completely clear you could use a boolean variable such as countdownRunning in addition to the interval variable to keep track of whether the countdown is active or not.
Try this:
$('#textArea').on('input propertychange', display30Seconds);
var interval=false;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$(document).on('click','#counterIsDone', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
interval=false;
}
}, 1000);
}
You can improve your code by using a conditional recursive call to to your iterative function instead - each call has a one second delay, which makes it slightly more intuitive to use (think of each call as one tick):
var seconds = 3;
$('#textArea').on('input propertychange', setTimeout(timeout.bind(null, seconds), 1000));
function timeout (iterations) {
$('#counter').html(iterations);
if (iterations === 0) {
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
timeout(seconds);
});
}
else {
setTimeout(timeout.bind(null, --iterations), 1000);
}
}
The bind function simply binds the arguments of the bind function to the arguments of the timeout call - the first argument to the bind function declares its this scope; but don't worry about that too much.
You can modify the duration of the timer by changing the seconds var. Hope this helps :)

delay the on("click") event

I have this code
$("input").on('keyup', function () {
$("block"),slideDown("slow")......
The problem is taht when I write fast the block will do the "animation" again and agin much slower than I write
Is there another event I can use to only run the code "after I'm finished writing" lets say, I stop writing and then it taks 500ms and then the code is executed.
function throttle(fn, time ){
var timer = 0;
return function() {
clearTimeout(timer);
timer = setTimeout($.proxy(fn, this), time);
};
}
$("input").on('keyup', throttle(function () {
$("block").slideDown("slow")
},500));
The throttle returns a new function that calls the old function once 500 milliseconds have elapsed since the function was last called.
Something like this is what I've used before:
$(input).keyup(onKeyUp);
/**
* Handler for the keyup event
*/
function onKeyUp() {
//reset
clearTimeout(myTimer);
myTimer = setTimeout(otherFunction, 500);
}
Now otherFunction will be called after 500 milliseconds, but on each keyup event this timer will be reset.
Try to use...
function slideDown(){
...
}
// call
setTimeout(function(){ slideDown(); }, 1000);

How to auto refresh HTML only if there has been no activity on a page?

I have a website which I would like to auto refresh ONLY if user is not using it for a specific time (ie.180 sec).Is there a way to auto refresh HTML only if there has been no activity on a page?
Thank you!
Two approaches:
1. Use a once-a-second timer and a "timeout" value.
You probably want to wrap this up in an object:
var activityHandler = (function() {
var timerHandle = 0,
timeout;
flagActivity();
function start() {
stop();
flagActivity();
timerHandle = setInterval(tick, 1000);
}
function stop() {
if (timerHandle != 0) {
clearInterval(timerHandle);
timerHandle = 0;
}
}
function flagActivity() {
timeout = new Date() + 180000;
}
function tick() {
if (new Date() > timeout) {
stop();
location.reload();
}
}
return {
start: start,
stop: stop,
flagActivity: flagActivity
};
})();
Then start it on page load:
activityHandler.start();
And ping it every time you see "activity":
activityHandler.flagActivity();
So for instance, you might do this:
if (document.addEventListener) {
document.addEventListener('mousemove', activityHandler.flagActivity, false);
}
else if (document.attachEvent) {
document.attachEvent('onmousemove', activityHandler.flagActivity);
}
else {
document.onmousemove = activityHandler.flagActivity;
}
2. Use a timer you reset every time there's "activity".
This is less ongoing work (we don't have something happening every second), but more work when you flag that activity has happened.
Set up a timer to do the refresh:
var handle = setTimeout(function() {
location.reload();
}, 180000);
...and then cancel and reschedule any time you see whatever you consider to be "activity":
clearTimeout(handle);
handle = setTimeout(...);
You can wrap this up in a function:
var inactivityTimerReset = (function() {
var handle = 0;
function reset() {
if (handle != 0) {
clearTimeout(handle);
}
handle = setTimeout(tick, 180000);
}
function tick() {
location.reload();
}
return reset;
})();
// Kick start
inactivityTimerReset();
// ...and anywhere you see what you consider to be activity, call it
// again
inactivityTimerReset();
Then, again, ping it on every activity. But this is a lot more work than I'd put in a mousemove handler, hence solution #1 above.
var docTimeOut;
function bodyTimeOut()
{
docTimeOut=setTimeout(function(){location.reload();},18000);
}
function resetTimeOut()
{
clearTimeout(docTimeOut);
bodyTimeOut();
}
document.onload = bodyTimeOut;
document.body.onmouseover= resetTimeOut;
you could declare a variable pageActive or something, set it to false, and whenever user does something set it to true.
Then, set a function to execute periodically as frequently as you want with setinterval() that checks this variable, if it's true set it to false to start again, if is false then refresh page.
You can use onblur and onfocus on body element to see if there is a kind of activity on your page.

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