I am trying to write a code that could use voice input and based on input can migrate to another page.
My code is not waiting when timeout is used and without timeout,the code is not waiting for input.
HTML Page:
<script src="Content/SpeechRecognisation.js" type="text/javascript"></script>
<script src="Content/SpeechUtterance.js" type="text/javascript"></script>
<script src="Content/LoginScript.js" type="text/javascript"></script>
<script src="Content/Additional.js" type="text/javascript"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body onload="Typer()"></body>
Javascript code in Js file:
function LoginPageSpeech() {
pageName = 'LoginPage';
controlPointer = "1";
var CPR_No = final_transcript;
$("#txtCPRNo").val(final_transcript);
var pageDetail = "Entered CPR Number is " + final_transcript;
CustomerResponse = final_transcript;
speak(pageDetail);
setTimeout(function(){},4000);
speak("if details are correct ,please say yes else say no after beep");
setTimeout(function () { SoundMake(); }, 4000);
setTimeout(function() {startDictation(event);},3000);
setTimeout(function() { },4000);
if (final_transcript == "YES") {
setTimeout(AuthenticationMsg,7000);
}
else
{
// setTimeout(function () { speak("Sorry.Please repeat again after beep"); }, 4000);
// setTimeout(function () { SoundMake(); }, 3000);
// setTimeout(function () { startDictation(event); }, 3000);
//
// LoginPageSpeech();
}
}
function Typer() {
pageName = "LoginPage";
speak('Welcome ,Please Speak your CPR Number after a beep');
setTimeout(function () { SoundMake(); }, 4000);
timeOutValue = 9000;
setTimeout(function () { startDictation(event); }, 4000);
}
function SoundMake() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclF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8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
}
You use setTimeout in the wrong way. For instance, look at this part:
setTimeout(function(){},4000);
speak("if details are correct ,please say yes else say no after beep");
setTimeout(function () { SoundMake(); }, 4000);
setTimeout(function() {startDictation(event);},3000);
setTimeout(function() { },4000);
It seems like you expect the execution to halt for 4 seconds on the first line, and only then continue with the second. But that is not true. The only thing that gets delayed is the function you pass as argument to setTimeout: it will be called later. But the engine will immediately continue with the next statement. In fact, none of the functions you pass to setTimeout can execute before all the remaining code has been executed.
So... now you can see the first line of the block above is quite useless. It says: "do nothing 4 seconds from now, and now continue with the next statement".
How to fix
There are several ways, some ugly, some nice, some in between:
1. Cumulate the time to delay
Knowing that all your setTimeout calls execute at practically the same time, specify a delay that also counts for the previous delays:
setTimeout(function(){
speak("if details are correct, please say yes else say no after beep");
},4000);
setTimeout(function () { SoundMake(); }, 4000+4000);
setTimeout(function() {startDictation(event);},4000+4000+3000);
setTimeout(function() {
// ...etc
},4000+4000+3000+4000);
The downsides are:
When you change your mind on one delay you need to adapt it at several places. You could counter this by using a variable, which you increase with the next delay.
When one of the scheduled actions takes a lot of time (or the browser gets busy with other stuff), the interval between actions might get a lot smaller than expected.
2. Nest the callbacks
Here you put the next actions inside the previous callback provided to setTimeout:
setTimeout(function(){
speak("if details are correct, please say yes else say no after beep");
setTimeout(function () {
SoundMake();
setTimeout(function() {
startDictation(event);
setTimeout(function() {
// ...etc
}, 4000);
}, 3000);
}, 4000);
}, 4000);
The downside is:
The so-called "callback hell": your code can get very deeply nested, and in extreme cases your editor might show mostly white space, with your code only becoming visible if you scroll to the right. This is not practical.
3. Recursion
Here you keep invoking the same function which you call again when the next timer ticks:
(function loop(i) {
var delay = 300;
switch (i) {
case 0:
// Do nothing, just launch the setTimeout
break;
case 1:
speak("if details are correct, please say yes else say no after beep");
break;
case 2:
SoundMake();
delay = 300;
break;
case 3:
startDictation(event);
break;
default:
// etc...
return; // start no more timeout
}
setTimeout(loop.bind(null, i+1), delay);
})(0); // start with 0
The downside is:
The switch statement is a quite verbose. You could alternatively create an array of objects, where each object has the code to execute as a function property, and the delay as another property. Then you could just index that in the loop body.
4. Promises
Since ES6 there is a Promise object, which many programmers would advise using for this purpose, myself included:
// Utility to get a promise object that resolves after a given delay
function promiseDelay(delay) {
return new Promise(function (resolve) {
setTimeout(resolve, delay);
});
}
promiseDelay(400)
.then(function() {
speak("if details are correct ,please say yes else say no after beep");
return promiseDelay(4000);
}).then(function () {
SoundMake();
return promiseDelay(3000);
}).then(function () {
startDictation(event);
return promiseDelay(4000);
}).then(function () {
// etc...
});
This code is quite clean and lean.
Remarks
Note that the above tackles just part of your code. You have the same issues in the Typer function. But the principle is the same. Take your preferred solution and apply it throughout.
Related
I am reading a project that I have to work and do additional work on, but I don't understand some interval trickery that has been done and not explained by the previous person. That's the code:
var intervalId;
var intervalIdtwo;
$(document).on('click', 'li.mention-individuals', function() {
clearInterval(loadTimer);
var otheridFromSearch = $(this).data('profileid');
var searchImage = $(this).find('img.search-image').attr('src');
var searchName = $(this).find('.mention-name').text();
$('.users-right-pro-pic img').attr('src', searchImage);
$('.users-right-pro-name').text(searchName);
$('.user-info').attr("data-otherid", otheridFromSearch);
xyz(useridd, otheridFromSearch, abc);
$.post('http://localhost/facebook/core/ajax/message.php', {
showmsg: otheridFromSearch,
yourid: useridForAjax
}, function(data) {
$('.msg-box').html(data);
$('.user-show').empty();
$('.top-msg-user-photo img').attr('src', searchImage);
$('.top-msg-user-name').text(searchName);
scrollItself();
})
if (!intervalId) {
intervalId = setInterval(function() {
loadMessageFromSearch(useridForAjax, otheridFromSearch);
}, 1000);
clearInterval(intervalIdtwo);
intervalIdtwo = null;
} else if (!intervalIdtwo) {
clearInterval(intervalId);
intervalId = null;
intervalIdtwo = setInterval(function() {
loadMessageFromSearch(useridForAjax, otheridFromSearch);
}, 1000);
} else {
alert('Nothing found');
}
})
function loadMessageFromSearch(useridForAjax, otheridFromSearch) {
var pastDataCount = $('.past-data-count').data('datacount'); //if no new data, the old messages will be shown
$.ajax({
type: "POST",
url: "http://localhost/facebook/core/ajax/message.php",
data: {
showmsg: otheridFromSearch,
yourid: useridForAjax
},
success: function(data) {
$('.msg-box').html(data);
}
})
$.post('http://localhost/facebook/core/ajax/message.php', {
dataCount: otheridFromSearch,
profileid: useridForAjax
}, function(data) {
if (pastDataCount == data) {
console.log('data is same');
} else {
scrollItself();
console.log('data is not same');
}
})
}
I generally get the code, but the Ifs section with the IntervalId and IntervalIdTwo - I have no clue what it does. Any tips or explanations would be greatly appreciated!
On the surface, the setInterval function is simple: it takes a function and a number n and calls the function (at most) every n milliseconds. It also returns a "handle" that allows you to cancel the repeated invocations by calling clearInterval with the handle.
For instance, here is a function that logs a string to the console:
function sayHello() {
console.log('hello!');
}
We can call it every second (1000 milliseconds) like so:
setInterval(sayHello, 1000);
(You can even try it out in your browser's dev. tools right now! It should print 'hello!' every second)
What if we want to stop printing 'hello!'? If we "hold onto" the return value, we can cancel the repeated invocations:
const handle = setInterval(sayHello, 1000);
(If you're curious, try printing handle!)
To cancel the process, call the clearInterval function with the handle:
clearInterval(handle);
A couple of notes:
In a lot of cases, it is a pain to define a separate function like sayHello, so we would instead use an "anonymous function", like:
setInterval(function() {
console.log('hello!');
}, 1000);
// or
setInterval(() => console.log('hello!'), 1000);
This underscores the fact that setInterval is a higher-order function: it takes another function as one of its arguments. This can take some getting used to, but with practice it becomes second nature.
Depending on how "busy" your browser is, the invocations may not take place at exactly the interval you specify. The delay may be longer than the number you provide, but never shorter (see 3. below for why).
if you really want to grok setInterval you will need an understanding of JavaScript's concurrency model.
I have 3 settimeout functions in one function.
The one calling the fades() works fine, not the one with the comments surrounded.
This is what I wanted it to do: first, play the loading bar. Next, fade the bar out and show a button.
The load bar didn't quite work but after that a button should have toggle_visibility(), which would show it.
<script>
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
};
function fades() {
//problem settimeout
setTimeout(function(){
$('#button1').toggle_visibility();
}, 5500);
// end of problem
setTimeout(function() {
playDemo('disney', 2, disneyInterval);
}, 1000);
setTimeout(function() {
$('#mydiv').fadeOut();
}, 5000);
};
setTimeout(function() {
fades();
}, 10);
</script>
$('#button1').toggle_visibility();
This code means function toggle_visibility is a function of jQuery. But in your code, it is just a function.
You can invoke it like toggle_visibility('button1'). This will change button1's display once.
toggle_visibility(button1)
"toggle_visibility" is not a function for jquery! so $().toggle_visibility is undefined
1) To verify whether your callback function is being called or not, you simply place a console.log inside it with something like "function XXX called".
2) The timing in setTimeout is not perfect. It guarantees that your function will not be called before that time you specified has passed but does NOT guarantee it to be exactly at the requested time.
So if you just say:
setTimeout(f2, 500);
setTimeout(f3, 600);
It does not guarantee that f3 will be called exactly 100ms after f2.
If you try to rely on this to run animations, they will not always be smooth.
If you need to "chain" calls, let each callback call the other.
setTimeout(function() {
console.log("Function 1");
// do stuff
setTimeout(function() {
console.log("Function 2");
// do stuff
setTimeout(function() {
console.log("Function 3")
// do stuff
},0);
}, 500);
}, 1000)
Nested callbacks are nasty to read/write though, so you can flatten it out
function f1() {
console.log("Function 1");
// do stuff
setTimeout(f2, 500)
}
function f2() {
console.log("Function 2");
// do stuff
setTimeout(f3, 1000)
}
function f3() {
console.log("Function 3")
// do stuff
}
setTimeout(f1, 1000)
That's right guys. As was said before, here what you can do - implement this function to jQuery:
function toggle_visibility(id) {
var e = $('#'+id);
if (e.css('display') == 'block'){
e.css('display', 'none');
}
else {
e.css('display', 'block');
}
}
jQuery.fn.toggle_visibility = function() {
return toggle_visibility(this.attr('id'));
}
Now you can use it like you used)
I stumbled upon a problem:
the code is supposed to output "hi1" "hi2" "hi3" "hi4" in that order.
I wrote this simplified code, the actual code is more complicated and causes me to not be able to remove some of the functions I marked.
function test() {
console.log("hi2");
setTimeout(function () { //maybe replace this?
console.log("hi3");
}, 2000);
}
console.log("hi1");
test();
setTimeout(function () { //cannot get rid of this
console.log("hi4");
}, 0);
how do I make it output in order?
If you need to wait for setTimeout in your test() to execute before continuing, the easiest way is to use callback:
function test(callback) {
console.log("hi2");
setTimeout(function () {
console.log("hi3");
// Execute additional logics
callback();
}, 2000);
}
console.log("hi1");
test(function () {
setTimeout(function () {
console.log("hi4");
}, 0);
});
Use the callback or try to show your complicated code is more. We can help you to analyze it.
As others have pointed out setTimeout is asynchronous so they run in the background while the rest of the code continues. I'd guess that at the moment you get something like:
hi1
hi2
hi4
then a 2000ms delay, then
hi3
If you can't change the code much then try changing the delay for hi4 to 4000 like:
setTimeout(function () { //cannot get rid of this
console.log("hi4");
}, 4000);
That should fix the order, but it's still pretty messy and unreliable. I'd rather have something like:
function showMessage(msg, delay) {
setTimeout(function() {
console.log(msg);
}, delay);
}
showMessage('hi1', 0);
showMessage('hi2', 2000);
showMessage('hi3', 4000);
showMessage('hi4', 6000);
function ShowColoursScreen() {
setSquaresList()
$("#ModeOne").hide();
$("#ModeTwo").show();
setTimeout(function () {
$("#ModeOne").show();
$("#ModeTwo").hide();
setTimeout(function () {
ShowColoursScreen();
}, 1500);
}, 15000);
}
This is very very weird, Im wanting to rotated between two divs every 15 seconds (i dont want to use js intervals). However after the first fifteen seconds ShowColoursScreen(); runs without waiting the second 15 seconds (if that makes sense). Its like the timeout gets ignored, any ideas?
Your code is correct. However, the inner timeout just waits for 1.5 seconds as you forgot a zero. Simply replace the 1500 with 15000.
You can also simplify the call a bit - as you do not have any arguments there is no need for the anonymous function: setTimeout(ShowColoursScreen, 15000);
function ShowColoursScreen($elements) {
if(!$elements instanceof jQuery) {
$elements = $($elements);
}
var current = 0;
// What does this function do?
setSquaresList();
function showCurrent () {
var $currentElement = $($elements[current]);
$elements.not($currentElement).hide();
$currentElement.show();
(current++) % $elements.length;
setTimeout(showCurrent, 15000);
}
showCurrent();
return $elements;
}
ShowColoursScreen('#ModeOne, #ModeTwo')
I have the following scenario:
setTimeout("alert('this alert is timedout and should be the first');", 5000);
alert("this should be the second one");
I need the code after the setTimeout to be executed after the code in the setTimeout is executed. Since the code that comes after the setTimeout is not code of my own I can't put it in the function called in the setTimeout...
Is there any way around this?
Is the code contained in a function?
function test() {
setTimeout(...);
// code that you cannot modify?
}
In that case, you could prevent the function from further execution, and then run it again:
function test(flag) {
if(!flag) {
setTimeout(function() {
alert();
test(true);
}, 5000);
return;
}
// code that you cannot modify
}
I came in a situation where I needed a similar functionality last week and it made me think of this post. Basically I think the "Busy Waiting" to which #AndreKR refers, would be a suitable solution in a lot of situations. Below is the code I used to hog up the browser and force a wait condition.
function pause(milliseconds) {
var dt = new Date();
while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}
document.write("first statement");
alert("first statement");
pause(3000);
document.write("<br />3 seconds");
alert("paused for 3 seconds");
Keep in mind that this code acutally holds up your browser.
Hope it helps anyone.
Using ES6 & promises & async you can achieve running things synchronously.
So what is the code doing?
1. Calls setTimeOut 1st inside of demo then put it into the webApi Stack
2. Creates a promise from the sleep function using the setTimeout, then resolves after the timeout has been completed;
3. By then, the first setTimeout will reach its timer and execute from webApi stack.
4. Then following, the remaining alert will show up.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
setTimeout("alert('this alert is timedout and should be the first');", 5000);
await sleep(5000);
alert('this should be the second one');
}
demo();
Just put it inside the callback:
setTimeout(function() {
alert('this alert is timedout and should be the first');
alert('this should be the second one');
}, 5000);
No, as there is no delay function in Javascript, there is no way to do this other than busy waiting (which would lock up the browser).
ES6 (busy waiting)
const delay = (ms) => {
const startPoint = new Date().getTime()
while (new Date().getTime() - startPoint <= ms) {/* wait */}
}
usage:
delay(1000)
You can create a promise and await for its fulfillment
const timeOut = (secs) => new Promise((res) => setTimeout(res, secs * 1000));
await timeOut(1000)
Here's a good way to make synchronous delay in your code:
async function yourFunction() {
//your code
await delay(n);
//your code
}
function delay(n) {
n = n || 2000;
return new Promise(done => {
setTimeout(() => {
done();
}, n);
});
}
Found it here Right way of delaying execution synchronously in JavaScript without using Loops or Timeouts!
setTimeout(function() {
yourCode(); // alert('this alert is timedout and should be the first');
otherCode(); // alert("this should be the second one");
}, 5000);
I think you have to make a promise and then use a .then() so that you can chain your code together. you should look at this article https://developers.google.com/web/fundamentals/primers/promises
You could attempt to replace window.setTimeout with your own function, like so
window.setTimeout = function(func, timeout) {
func();
}
Which may or may not work properly at all. Besides this, your only option would be to change the original code (which you said you couldn't do)
Bear in mind, changing native functions like this is not exactly a very optimal approach.