Javascript - call a function when you finish typing - javascript

Let's say I have an input in wich the user is going to type some text. When he finish typing I want to call a function automatically.
This is what I have done till now:
<input type="text" oninput="change();"/>
<script>
function changing(){
alert('You stoped typing!');
}
function change(){
clearTimeout(changing);
setTimeout(changing, 2000);
}
</script>
What I am expecting :
When you type, change is called. It cancels the last changing that was supposed to run in 2 seconds and run a new changing within 2 seconds.
What actually happens :
When you type, change is called. It doesn't cancel the last changing that was supposed to run in 2 seconds but still run a new changing within 2 seconds. As you type, the first alert window will appear 2 seccond after you start typing and keep showing again and again one after another.
Is there something wrong in my code?

setTimeout() returns a timer ID. It is that timer ID that you must pass to clearTimeout() for it to work properly (you are passing the callback function to clearTimeout() and that is not how it works).
So, you need to store the return value from setTimeout() into a variable in a lasting scope that you can then later pass to clearTimeout() like this:
<input type="text" oninput="change();"/>
<script>
function changing(){
alert('You stoped typing!');
}
var timer;
function change(){
clearTimeout(timer);
timer = setTimeout(changing, 2000);
}
</script>

The setTimeout() function returns a value that must be used later with clearTimeout() if you need to cancel it.
var timer;
function changing(){
alert('You stoped typing!');
}
function change(){
clearTimeout(timer);
timer = setTimeout(changing, 2000);
}

Related

How to trigger a call when typing is stopped

<input autocomplete="off" [config]="config2" [items]="items2" (inputChangedEvent)="onInputChangedEvent($event)" (selectEvent)="onSelect($event)">`enter code here`
onInputChangedEvent(val: string) {
this.changeEvent.emit(val);
this.inputChanged = val;
if (this.timer) {
clearTimeout(this.timer);
}
// trigger the search action after 400 millis
this.timer = setTimeout(this.searchFunction(val), 200);
}
I am using InputChangedEvent ,how can we delay the event
You can't pass a function with arguments to setTimeout(), you need to create another function where in you call this function:
var _this = this;
setTimeout(function () {
_this.searchFunction(val);
}, 200);
By passing the function directly to setTimeout, JavaScript executes the function and uses the return value as the callback. So your searchFunction is executed every time.
Are you asking how to trigger the action only if there has been no typing for 400msec?
If so, the usual approach is a "deadman's switch" (name borrowed from an old safety device on trains, I believe).
The basic idea is that each time you see a keystroke, you kill the existing timer (if any) and start a timer for 400msec.
Then, if the timer finally triggers, you know that 400msec have passed without a keystroke, and you can do the action.

jquery pause before displaying next step

On button next click (Game context), I want to make pause to show correct answer before showing next question. how can I do it?
I try this :
showCorrectAnswer();
questionCounter++;
setTimeout(displayNext(), 6000);
/* Or */
showCorrectAnswer();
questionCounter++;
wait(6000);
displayNext();
/*with wait*/
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
But does not work.
Thanks
You are supposed to pass either an anonymous function to setTimeout() (in which you place what you want to execute when the timeout expires) or the name of a defined function. If you place () after the name, as you did, the function is executed when the setTimeout() is parsed, not when it expires, expecting the result of running your function to return another function that will be executed when the setTimeout() expires - much like the anonymous function does.
Either of the following will work as expected. Name of function:
showCorrectAnswer();
questionCounter++;
setTimeout(displayNext, 6000);
...or anonymous wrapper:
showCorrectAnswer();
questionCounter++;
setTimeout(function(){
displayNext();
}, 6000);
In most real life scenarios, it is advisable to change questionCounter value inside the displaynNext() function, not before.
With jquery you can use:
$('.container').hide().delay(6000).fadeIn(displayNext());
check out this
you have done a small mistake setTimeout(displayNext(),6000) which calls immediately instead you should only pass function name. setTimeout(displayNext,6000)
If you want to do call with parameters make sure you write as a function and then put all your code inside it setTimeout(function(){displayNext(parameter1,parameter2);},6000)
function displayNext(){
alert("display");
}
<input type="number" step="1000" id="num_milisecond" value=1000> milliseconds
<input type="button" onclick="setTimeout(displayNext, document.getElementById('num_milisecond').value);" value="click to allert">

How to stopp every running javascript function (also inline)

Hi I'm trying to create a script which can stop every Javascript function.
e.g
<button onclick='doSomething()'></button>
or
setInterval(doSomething, 200);
Is it possible to stop and disable those functions with another Javascript-File
I mean get every interval like getElementByTanName(interval) and the a for function to clear them all
You need assing interval to variable, then you will be able to stop it using clearInterval function.
var interval = setInterval(function, 5000)
if(finished){
clearInterval(interval);
}

returning setTimeout to stop later doesn't work as my expectation?

Here's a simple html&javascript: When I click on the "start" button, the counter starts, the number displayed being incremented, then when I click on the "start" again, the counter resets and starts all over again. (This is just a practice with setTimeout and I don't intend to use this as anything.) At first I forgot to stop mainloop and was running another mainloop every time the button is clicked, which resulted in accelerated counting after repeated clicks. I saw this question (javascript - How to stop a setTimeout loop?) and managed to make it work.
And then I changed the javascript slightly. I thought these codes are almost equivalent, but it wasn't --- it no longer worked, multiple mainLoop seemed to be running after clicks. My question: why are these not equivalent? Why isn't the latter working?
Working codes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<pre id="start" style="background-color:green; width:70px; text-align:center;">Start</pre>
<pre id="count"></pre>
</div>
<script src="main.js"></script>
</body>
</html>
main.js
var counter = 0;
var timer;
function mainLoop(){
counter++;
document.getElementById("count").innerHTML=counter;
timer = setTimeout(mainLoop,100);
}
function start(){
if (timer){
// stop mainLoop that is currently running.
clearTimeout(timer);
}
// and start again.
counter = 0;
mainLoop();
}
document.getElementById("start").addEventListener("click",start);
Then I changed:
var counter = 0;
var timer;
function mainLoop(){
counter++;
document.getElementById("count").innerHTML=counter;
return setTimeout(mainLoop,100); // changed here
}
function start(){
if (timer){
clearTimeout(timer);
}
counter = 0;
timer = mainLoop(); // and here
}
document.getElementById("start").addEventListener("click",start);
mainLoop is Looping itself, without setting the timer that's why.
Every-time the setTimeout get a new value , while you are stopping a old Timer if you don't update it.
You may wanna look into setInterval() instead thou, don't need repeatedly create Timer.
Your code will work the first time mainLoop is called as the value is returned. The second time it is called it is called from setTimeout, which means that the returned value (the value of the new timeout) is lost.
When you try to clear the timeout, you're trying to clear it using the value obtained from the very first call, which is a timeout which is passed in any case, not the current timeout value.
Try setting timer in your mainLoop.
You execute clearTimeout(timer)
before you set timer = mainLoop();
also i believe timer = mainloop() just runs the mainLoop function again timer is only the timeout function..
it look's like you're using setTimeout as an interval maybe you should look at this..
jQuery setInterval()
The reason you are getting multiple mainLoop's is because in the mainLoop, you are telling it to call itself every 100 milliseconds. Then it's returning setTimeout to itself, instead of returning it to the start method.
So you end up calling setTimeout more than once, but you arent storing the return value, which you need to pass to clearTimeout to cancel the loop.
What you could do is have something like the following:
function mainLoop() {
counter++;
document.getElementById("count").innerHTML=counter;
}
function start() {
if (timer){
clearTimeout(timer);
timer = undefined;
counter = 0;
} else {
timer = setInterval(mainLoop(), 100); // Set interval calls it every 100 milliseconds until it is cancelled
}
document.getElementById("start").addEventListener("click", start, false);

how to reload javascript code block

I need to reload a block of javascript every amount of time.. say
<script type="text/javascript">
var frame = some sort of code;
</script>
i need that block of any function to be reloaded every 15 seconds without reloading the page itself .. something like jQuery time out but i don't know how to apply it..
any idea?
var frame;
setInterval(function() {
frame = someSortOf.Code();
}, 15000);
That will execute the provided function every 15 seconds, setting your value. Note the var frame is declared outside the function, which gives it global scope and allows it to persist after your function executes.
You should not really "reload" a script. What you really want to do is simply run an already loaded script on a set interval.
function foo() {
// do something here
if (needRepeat) {
setTimeout(foo, 15000);
}
}
setTimeout(foo, 15000);
You can use setTimeout('function()', 15000); - put this line of code at the end of the function() so that it calls itself again after 15000ms.
The other way is just to call setInterval('function()', 15000); and this will call your function() every 15000ms.
The difference between the first and the second one is that the first calls the function after specific milliseconds (only once, so you need to insert it in the function itself) and the second one just calls the function every n milliseconds.

Categories

Resources