How to kill a process in javascript? - javascript

Let's take an example (i am not asking how to cancel/kill a setTimeout at all, i just use it to represent different processing times of different tasks):
<div id="content">
</div>
<p>Which color do you prefer ?</p>
<button id="long" onClick="long_process();">Blue</button>
<button id="short" onClick="short_process();">Red</button>
<script>
function long_process() {
setTimeout(function() {
$('div#content').text('My favorite color is blue');
}, 10000);
}
function short_proccess() {
setTimeout(function() {
$('div#content').text('My favorite color is red');
}, 1000);
}
$('button#long').click();
$('button#short').click();
</script>
Regarding this example, you probably know already what i am going to ask, how can we stop the long processing action if the user launch a short processing action which is supposed to take over it ?
In this example, if the favorite color of the user is red, but the user click the wrong (blue) button, then click the red button, the blue color willl be the last color displayed because its process is longer.
I know how to manage it with C/C++ using the pthread library, but i have no idea with javascript, and it's very important in some situation to be 100% sure about what your app will display.
Thanks !

When creating a timer, setTimeout and setInterval return an ID that you can use to reference that timer:
var long_timer;
function long_process() {
long_timer = setTimeout(...);
}
When you want to stop that timer, pass that ID into clearTimeout or clearInterval:
if (long_timer) {
clearTimeout(long_timer);
}

Related

Make <p> disappear after certain amount of time using JS or JQuery

I'm working on a project that requires me to show and hide text. I want one verse to appear on the screen, disappear after x amount of time, and then new text appears. I'm pretty new to Javascript & JQuery so I'm not really sure how to make this work. Below is the code I have so far:
HTML
<p class="mast__text js-spanize" id="verse1">
Magnetic light in the blue-high haze
</p>
<p class="mast__text js-spanize" id="verse2">
A magnifying glass upon my face
</p>
<p class="mast__text js-spanize" id="verse3">
It's so hot I've been melting out here
</p>
JS:
$("#verse1").show();
setTimeout(function() { $("#verse1").hide(); }, 2000);
$("#verse2").show();
setTimeout(function() { $("#verse2").hide(); }, 2000);
$("#verse3").show();
setTimeout(function() { $("#verse3").hide(); }, 2000);
Both functions seem to be called at the same time which is making the text appear and disappear at the same time. I'm sure that there is an easy fix to this that I'm overlooking, but I've looked online and can't seem to figure this out.
The issue is that the code assumes that the setTimeout function waits for the time to finish. Instead, the code continues on, an makes note to run the code after a specified time. To fix it, you simply need to nest the setTimeout functions:
$("#verse2").hide(); // So these aren't showing at the start
$("#verse3").hide();
$("#verse1").show();
setTimeout(function() {
$("#verse1").hide();
$("#verse2").show();
setTimeout(function() {
$("#verse2").hide();
$("#verse3").show();
setTimeout(function() { $("#verse3").hide(); }, 2000);
}, 2000);
}, 2000);

How to ensure sequence of commands run sequentially (Timeout issue in jQuery - Qualtrics)

I am designing an experiment in qualtrics using java script. For each question in my study, a participant needs to guess the correct answer, type it in, and then hit the space button. Once they hit the space button, a logic checks whether their answer is correct or not. If the answer was correct, a sound should be played for 1.2 seconds, the background color should change into red for a second and then back to white, and lastly the experiment should automatically moves on to the next question.
So far, I figured out the correct sequence of commands. However, it seems like i am not using the setTimeout logic correctly. no matter what combination of timeout values I used, I couldn't get it play all the middles steps, including the audio play and red background flash, before the screen moves to the next question.
Here, I 've shared my code. I would very much appreciate any help.
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
});
Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
var qid = this.questionId;
var changepage = null;
/*focus on the box*/
jQuery("#"+qid+" .InputText").select().focus();
document.onkeydown = function(event) {
console.log('keydown',event);
if (event.which == 32) { //hit the space button
event.preventDefault();
//read the input
input = jQuery("#"+qid+" .InputText").val();
console.log(input);
if (input.trim().toLowerCase() == "cat") {
//alert(input.trim().toLowerCase());
document.getElementById("correct").play(); //play the correct sound which is 1.2seconds long
setTimeout(jQuery("body").css("background-color","red"), 3000); // change the background color
setTimeout( jQuery('#NextButton').click(), 2000) //move on to the next question
} //end of if
} // end of if 32
} //end of down button
});
Qualtrics.SurveyEngine.addOnUnload(function()
{
jQuery("body").css("background-color","white");
});
setTimeout is asynchronous. If you want multiple setTimeouts to execute in a fixed order then the times have to be additive. So your NextButton timing should be 5000ms (3000ms + 2000ms).
Alternatively, you could put the NextButton click inside the background color change setTimeout function. To add to that, could you put both inside an 'ended' event on your audio.
if (input.trim().toLowerCase() == "cat") {
//alert(input.trim().toLowerCase());
//play the correct sound which is 1.2seconds long
vid.play();
vid.onended = function()
{
jQuery(".skirt").css("background-color","red");
jQuery('#NextButton').click();
};
} //end of if

What is this called, and how can I do it? (Changing text)

So as you can see on https://www.sketchapp.com/ they got something cool midway through the page, as you can see it changes the text automatically (Sketch is made for Chaning text here like you) after some time; and I was wondering how they did that and how it's called.
I'm trying to recreate something similar, Thanks
That you need is either a setInterval if you want the text to change on approximately the same time for an indefinite period or you setTimeout if you want to change the text only once. Below it is a snippet that uses the setTimeout as an example:
document.addEventListener('DOMContentLoaded', function(){
setTimeout(function(){
var div = document.getElementById('js-text');
div.innerHTML = "Replaced <span class='redText'>Text</span>";
}, 1000);
});
.redText{
color: red;
}
<div id="js-text">Initial Text</div>

SetInterval loop relatively confusing to me

HTML
<div id="backspace" ng-click="deleteString(''); decrementCursor();">
JS
<script>
$scope.deleteString = function() {
if($scope.cursorPosVal > 0){
//$scope.name = $scope.name - letter;
$scope.name = [$scope.name.slice(0, $scope.cursorPosVal - 1) + $scope.name.slice($scope.cursorPosVal)].join('');
console.log($scope.name);
setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30);
} else {
$scope.cursorPosVal = 1;
}
};
</script>
I am designing an on screen touchscreen keyboard. This is my backspace button. I am going to make it so that when you click and hold the backspace button, it starts removing characters automatically. I don't know where to begin with creating a setInterval, and I know a setInterval is exactly what I need to use here.
If I'm not wrong, you want that while you're keeping your button pressed, a function repeats itself.
You're right with setInterval(). However, the way you manage the event is wrong.
Take a look at this fiddle (It's not your code, but a simple example is the best way to understand):
http://jsfiddle.net/daq9atdd/1/
$(function(){
var interval = null;
$('#myButton').mousedown(function(){
interval = setInterval(function(){
console.log('Hello !');
}, 250);
});
$('#myButton').mouseup(function(){
clearInterval(interval);
});
});
I start the interval when the button is pressed, store it, and clear it when the button is released.
You’re so sure about setInterval.
If browser briefly hangs for whatever reason (say some background task), setInterval would go on queueing your backspace calls until it has some CPU time. This means user may see no change and hold backspace longer than needed, and then see a whole bunch of characters suddenly vanish when browser is back to normal.
Thus by setting a timeout after every call you’re making sure user won’t remove more characters than needed. Might be important if the goal is to improve UX.
Example implementation with AngularJS directives and setTimeout
See also:
setTimeout or setInterval?
noKid’s fiddle updated with setTimeout in mind

how to show a div only for 3 seconds and disappear again using jquery?

i have my html like this
<p id="msgfail" hidden="hidden" >Theres an error processing ur request</p>
<p id="sucessmsg" hidden="hidden">Success fully update database</p>
when i click a button it triggers attempt to enter data to mysql database. and the corresponding p item is made visible. now my question is how do i make it dissapear again after a timeout ?
i tried it this way
if ($("#msgfail").is(":visible")) {
setTimeout(function() {$("#msgfail").hide();}, 3000);
}
Is something like this what you're thinking?
$("#msgfail").delay(3000).hide(1);
Docs for delay.
You can just use setTimeout which is native to JavaScript.
$('#msgfail').show();
setTimeout(function() { $('#msgfail').hide(); }, 3000);

Categories