Categories: JavaScript

Simple Javascript Delay routine

Setup events to occur after a delay

Using setTimeout we can trigger an alert after 5000 milliseconds.

setTimeout("alert('hello guest!')",5000);

<form>
 <input type="button" value="Click for event" />
</form>

That’s the elegant way to handle delays, pauses and waiting in Javascript.

Setup a Javascript program to wait

The routine above doesn’t stop the Javascript routine from executing. It just sets up an event to happen later. But sometimes you find yourself thinking: It would be so much easier if I could just get Javascript to wait for a bit here and then carry on as before. It's a bit naughty, but I’ve written a script that does just that. Note: This script is not a good example of how to use Javascript. It consumes a huge amount of CPU power just going round in circles for a predetermined amount of time. You really should be using the technique above in nearly all cases, but this script can be handy for prototyping. Simple way:

<script language="javascript">

function dopause(msec) {
  msec += new Date().getTime();
  while (new Date() < msec){}
  } 

</script>

Call the routine dopause(5000) where 5000 is the number of milliseconds you would like the computer to pause. You're welcome to use this script on your site and to adapt it to suit.

SGH

At the same time, I can’t think of anything more satisfying than sitting in front of TV, eating take-away, lights down low, in my pyjamas and watching crap on TV. Basically, I strive to live a balanced life. Fun. Serious. Fast. Slow. Brainy. Bimbotic. Intense. Lazy. You get the drift.

Recent Posts

Free GG Mug Mockup

GG Mug Mockup designed for logo branding of companies and brands.

6 years ago

Lovtony Font Duo – Modern Sans Serif

A great font/script for creating beautiful logos, posters, wedding invitations, blog posts, social media, and…

6 years ago

Free Men T-Shirt Mockup

Realistic T-Shirt Mockup PSD which you can use freely to showcase your apparel design.

6 years ago

Classic Coffee Mug Mock-up Free PSD

Classic coffee mug Mock-up Free PSD. Free mug mockup PSD to showcase your branding design…

6 years ago

Juliette – Stylish Handwritten Signature Font

Juliette - Stylish Handwritten Signature Font

6 years ago

XXII Aven Sans Serif Font Family

XXII Aven Font Family - a new modern all-caps sans serif font with versatility in creativity.

6 years ago