Blue Orange Blue Orange - 8 months ago 54
Javascript Question

How to set time delay in javascript

I have this a piece of js in my website to switch images but need a delay when you click the image a second time. The delay should be 1000ms. So you would click the img.jpg then the img_onclick.jpg would appear. You would then click the img_onclick.jpg image there should then be a delay of 1000ms before the img.jpg is shown again.

Here is the code:

jQuery(document).ready(function($) {

$(".trigger").toggle(function () {
$(".trigger").find('img').prop('src', 'http://localhost:8888/images/img_onclick.jpg');
}, function () {
$(".trigger").find('img').prop('src', 'http://localhost:8888/images/img.jpg');
$(".trigger").click(function () {


Answer Source

Use setTimeout():

var delay=1000; //1 second

setTimeout(function() {
  //your code to be executed after 1 second
}, delay);

If you want to do it without setTimeout: Refer to this question.