Speech Recognition with Chrome

There are loads of posts online about Speech Recognition* but we have been having so much fun with it we wanted to highlight how easy it is to use.

*Compatibility is a big issue for any client work as it only really works in Chrome…


// Setup browser Speech Recognition
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
var recognition = new SpeechRecognition();
recognition.interimResults = true;
recognition.lang = 'en';

// Event listener for Speech results
recognition.addEventListener('result', function(event) {

// Add Speech Recognition results to var
var transcript = event.results[0][0].transcript;

// Display results in DOM
document.querySelector('.content').textContent = transcript;

}, false);

// Start speech recognition
recognition.start();

// Event listener to restart speech recognition each time user has stopped talking
recognition.addEventListener('end', recognition.start);

For a full list of setting see: https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition

Stop a function that has been started with javascript’s setTimeout() function

I created a scroll animation that I wanted to happen 3 seconds after the page had loaded. So I used the javascript setTimeout() function:

var scrollToContent = function() {
    var element = '#my-element';
    var elementOffset = $( element ).offset().top;

    $("html, body").animate( { scrollTop: elementOffset }, 1000 );
};

var initScroll = setTimeout( scrollToContent, 3000 );

However I wanted the function to stop if the user starts interacting with the page (ie. scrolling or clicking on things). To do this I used the clearTimeout() function:

// Write a function to stop initScroll
var stopScrollToContent = function() {
  clearTimeout( initScroll );
};

// Trigger stopScrollToContent when user clicks or scrolls
$( 'body' ).click( stopScrollToContent );
$( window ).scroll( stopScrollToContent );